Rails date equality not working in where clause
Say I have ModelA
and ModelB
. When I save an instance of ModelA
to the db it also creates/saves an instance of ModelB
. In the db I end up with 开发者_开发问答UTC for created_at
that show up exactly the same. eg:
puts ModelA.first.created_at # Wed, 31 Aug 2011 22:49:28 UTC +00:00
puts ModelB.first.created_at # Wed, 31 Aug 2011 22:49:28 UTC +00:00
So I'd expect a query like the following to return matching records (but it doesn't)
# model_instance is instance of SomeModel
ModelA.where(created_at:model_b_instance.created_at) # returns []
But something like this, using to_s(:db) does work
ModelA.each do |m|
if m.created_at.to_s(:db) == model_b_instance.created_at.to_s(:db)
... # found matches here
end
end
Can someone explain what I am doing wrong here? I want to be able to write queries like ModelA.where(created_at: ... )
but I'm currently stuck having to iterate and match against to_s(:db)
.
Two things to try:
- see what the created_at values are in the db -- maybe there's something off like the time zone (maybe rails is inferring a time zone for one but not the other)
- look in the rails log at the actual sql query that is being generated by your ModelA.where invocation -- maybe it's doing some sort of unexpected thing.
精彩评论