I was wondering, let’s say I have two models, discussions and post. Posts belong to discussions. I have a custom action in a Discussion model that acts to check the latest activity on an object by checking the creation date of its newest post. ie
def latest activity
self.posts.last.created_at || self.created_at
end
Can i write a scope that orders the model’s objects by this method rather than, say, a column in the Discussion model?
scope :latest_activity, #what to put here?
is there a reason why you don’t want to alter the parent? Rails have a built-in method called touch for this exact thing. For example: belongs_to :discussion, :touch => :last_reply_at will make it so whenever a reply is changed(created/updated) the parent will have that field updated with Time.now timestamp. One benefit of this would be the ability to not query the children every time you want to see which discussion has the last reply.
Have a look at http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
EDIT
Another way to do this would be to add a filter, for instance after_create on the post update a field with the current time on the discussion model.