AnApprentice
AnApprentice

Reputation: 111070

Rails - Building a ActiveRecord Query?

I have a model User and a model message.viewed_at

What I want 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

Upvotes: 0

Views: 260

Answers (2)

Ed Haywood
Ed Haywood

Reputation: 335

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

Upvotes: 1

jdl
jdl

Reputation: 17790

@user.messages.first(:order => "viewed_at desc")

Here are the docs.

@user.messages.where("viewed_at is not null").order("viewed_at desc").first

Upvotes: 2

Related Questions