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.* FROMcommentsINNER JOINitemsONcomments.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.
You need to replace
created_atwithcomments.created_atin your conditions. As you can see in the generated query, there are two tables joined:commentsanditems, they both havecreated_at. So your db is a little confused, which created at you are talking about.