开发者

Grouping messages to show latest in overview

I'm trying to show messages in an organized wa开发者_JAVA百科y in my rails 3 app. I'm trying to group the messages by a listing id and showing the latest message in that conversation belonging to the listing.

I'm trying this syntax in my controller:

@messages = Message.all(:conditions => { :recipient_id => current_user.id },
                        :group => :listing_id,
                        :order => "created_at DESC")

This successfully groups together my messages by listing, however it doesn't show the last message within that group. It shows the oldest one.

Does anyone know how to accomplish this? I've tried using the :having clause, but to no avail so far.


The most important thing to get familiar with when using ActiveRecord, is watching your output logs. If you're running your app off localhost, started by rails server, then you should be seeing all SQL outputted into your console.

I say 'check your SQL' because your approach doesn't quite make sense. If you want to only select a specific conversation and retrieve its last message, then you should doing something like this:

@messages = Message.all(:conditions => 
                      { :recipient_id => current_user.id,
                        :listing_id => params[:listing_id] },
                        :order => "created_at DESC")

If you're trying to get the last Message for each Listing, then you need to work from a different perspective, like so:

@listings = Listings.all(:conditions => {:recipient_id => current_user.id},
                         :include => :messages,
                         :order => 'messages.created_at DESC')

last_messages_of_first_listing = @listings.first.messages.first
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜