Hello,
I am using acts_as_commentable (related to Post) and I would like to
know how to get the list the posts ordered by date of comment (i.e.
post with recent comment first).
in addition if a post has no comment, i would it to be inserted based
on its creation date.
Thanks for your help
Nicolas
Here’s how I did it last night after about an hour of googling the
shit out of it and coming up empty.
First I load all the messages
@messages = Message.all
Then I loop through them all, and if a message has a comment,
I change the message’s created_at field to the comments created_at
@messages.each do |message|
comment = message.comments.find(:first, :order => ‘created_at
DESC’)
message.created_at = comment.created_at unless comment.blank?
end
Then I sort the messages by their (new) created_at dates, which
don’t
get saved so they don’t overwrite their real created_at fields.
@messages.sort! { |b,a| a.created_at <=> b.created_at }
Then I take the top 5 to use in my dashboard view.
@messages = @messages[0…4]
This works regardless of whether a Message (or Post in your case) has
any comments. This looks a little hackish to me, so please, Rails
gurus, have at it.
Hope this helps!
Morgan Currie
Message.all.sort_by { |m| m.comments.blank? ? m.created_at :
m.comments.last.created_at }[0…4]
Hi, it works fine witn ruby 2.x?? I’m very interested.
I read the it doesn´t work with this version, see this comments:
http://agilewebdevelopment.com/plugins/acts_as_commentable
and I´m using rails 2.0.2