I’m trying to write a little Messagecenter for my Project.
The problem I’m running into is that I only want to show the very last message from or to user, the one which came last will be shown.
The Table has a ID a Sender_ID, Receiver_ID and a MessageTXT.
Until now I have used:
@messages = Message.find_by_sql("select * from messages where id IN(SELECT MAX( id ) FROM messages WHERE sender_id = #{current_user.id} OR receiver_id = #{current_user.id} GROUP BY sender_id, receiver_id )")
Which gives me the last message to and the last message from a different user.
You should be able to do this with a named
scopeand not have to usefind_by_sqlwhich is really a last-resort tool.Example:
Using this you can retrieve the last one:
That should generate a query similar to what you have defined.