Hi

Try to write a scope for this something like 

Post < ActiveRecord::Base

has_many :comments

scope :active_posts, lambda {
  {
    :joins => :comments,
    :order => "comments.created_at desc"
  }
}

end

HTH

cheers

sameera

On Thursday, February 21, 2013 12:30:39 PM UTC+5:30, Alex Bayley 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] <javascript:> 
> http://growstuff.org/ 
> For personal stuff, please use [email protected] <javascript:> 
>

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