开发者

Rails - Building a ActiveRecord Query?

开发者 https://www.devze.com 2023-02-15 01:31 出处:网络
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.

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")
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号