Rails - Building a ActiveRecord Query?
I have a model User and a model message.viewed_at
What I wa开发者_JAVA技巧nt to do is given a user, determine when they last viewed a message if ever.
Given the user, I need to find all there messages, and then sort by the most recent viewed_at at the top, and then take that record and output the viewed_at timestamp if any.
@user = User.find(2)
@user.find(:first, :conditions => user.messages.viewed_at != nil)
But that doesn't work, suggestions? Thanks
@user.messages.first(:order => "viewed_at desc")
Here are the docs.
@user.messages.where("viewed_at is not null").order("viewed_at desc").first
The rails query guide is an excellent resource for this.
JDL's answer above will work. Also, not sure if min/max works on dates, but if so, the method below might be more efficient:
@user.messages.where("viewed_at is not null").maximum("viewed_at")
精彩评论