Not tested, and kinda dodgy, but ..

class Post
  scope :most_recently_active,
includes(:comments).order("max(comments.created_at, posts.created_at) DESC")
end

You should probably just go with the solution that you have right now. If
performance becomes a concern, I'd add an after_create hook on your Comment
class to update a datetime flag on the post itself, and then order on that
only.

Also re the below code:

   - convention is to do "def self.blah" when defining a class method (or
   use the class << self thing)
   - self.comments.last will not return the most recent comment unless you
   have a default scope ordering on your Comment class or relationship


On Thu, Feb 21, 2013 at 6:00 PM, Alex Bayley <[email protected]> wrote:

> I've got a Post class where I'm trying to display the most recently active
> posts.  "Recently active" is based on the created_at timestamp of the
> latest comment on that post, or if there are no comments, then on the
> created_at timestamp of the post itself.
>
> Here's what I've got:
>
>   def recent_activity
>     self.comments.last ? self.comments.last.created_at : self.created_at
>   end
>
>   def Post.recently_active
>     Post.all.sort do |a,b|
>       b.recent_activity <=> a.recent_activity
>     end
>   end
>
> Is it possible to turn this into a named scope?  I'm pretty sure order()
> won't take a calculated value.  I know about using lambdas in scopes, too,
> but can't see how to combine that with sorting/ordering.
>
> Any ideas?
>
> A.
>
> --
> Alex "Skud" Bayley
> [email protected]
> http://growstuff.org/
> For personal stuff, please use [email protected]
>
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby or Rails Oceania" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to 
> rails-oceania+unsubscribe@**googlegroups.com<rails-oceania%[email protected]>
> .
> To post to this group, send email to [email protected]**.
> Visit this group at 
> http://groups.google.com/**group/rails-oceania?hl=en<http://groups.google.com/group/rails-oceania?hl=en>
> .
> For more options, visit 
> https://groups.google.com/**groups/opt_out<https://groups.google.com/groups/opt_out>
> .
>
>
>


-- 
Michael Pearson

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
or Rails Oceania" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/rails-oceania?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to