I am building a simple messaging system with Rails3 that allows users to send private messages to each other. Each set of users can have a single stream of messages between each other (like texting)
I am confused however on the logic that is used to build the view that shows all current conversations going on for a user. This includes conversations that might only include sent messages from myself.
My schema has the following:
create_table "messages", :force => true do |t|
t.integer "from_id"
t.integer "to_id"
t.string "message"
t.datetime "created_at"
t.datetime "updated_at"
end
I would like to emulate something similar to FB messaging that shows a row for each conversation.`
Any ideas would be super helpful.
Thanks!
Danny
There are two sets of messages to consider:
from_idis the current user.to_idis the current user.I’d go with a
find_by_sqland let the database do all the work:An SQL UNION simply does a set-wise union of the two result sets so the above will grab all the users that
the_user_in_questionhas sent messages to and combine that with the users that have sent messages tothe_user_in_question; the result will be all the users that are involved in conversations withthe_user_in_questionas an array of User instances. Since there is anINon the UNION you can use UNION ALL to avoid a little bit of extra work in the UNION.You’d probably want to wrap that in a class method on Message:
And then you could just say things like:
in your controller.
You’ll want to add indexes to
messages.from_idandmessages.to_idin your database too.