Home Rails: Selecting user comments for the last day
Reply: 2

Rails: Selecting user comments for the last day

Alexander Savin
1#
Alexander Savin Published in 2011-08-25 16:51:00Z

I have User model. I have Comment model. Here is their relation:

User.rb:
  has_many :replies, :through => :items, :source => :comments

I'm trying to print out all replies of the User for the past day. This way:

user.replies.find(:all, :conditions => [" created_at between ? AND ?", Time.zone.now.beginning_of_day, Time.zone.now.end_of_day])

And here is the problem I get:

ruby-1.9.2-p180 :038 > bob.replies.all(:conditions => [" created_at between ? AND ?", Time.zone.now.beginning_of_day, Time.zone.now.end_of_day]) ActiveRecord::StatementInvalid: Mysql::Error: Column 'created_at' in where clause is ambiguous: SELECT comments.* FROM comments INNER JOIN items ON comments.item_id = items.id WHERE ((items.user_id = 16)) AND ( created_at between '2011-08-25 00:00:00' AND '2011-08-25 23:59:59')

It seems that the problem is because of my User - Comment relation. But I don't really get what's going on and how to fix this. Help is appreciated.

rubish
2#
rubish Reply to 2011-08-25 16:58:19Z

You need to replace created_at with comments.created_at in your conditions. As you can see in the generated query, there are two tables joined: comments and items, they both have created_at. So your db is a little confused, which created at you are talking about.

vise
3#
vise Reply to 2011-08-25 17:21:06Z

rubish is right; however you can also rewrite it as this:

User.replies.find(:all, :conditions => {:created_at => Time.zone.now.beginning_of_day..Time.zone.now.end_of_day})
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300627 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO