I created a private messages system but I am having trouble with the inbox. I want to create a regular inbox where you can see all your conversations. I tried to do something but I get a result of all the messages the user got but I want to display only the last message from each conversation.
SQL: I got messages table with id, user_id(int), to_id(int), content(text), read(boolean).
Messages Controller:
def inbox
@messages = Message.where("to_id = ? OR user_id = ? AND to_id != 0", current_user, current_user).order(created_at: :desc)
end
View:
<% @messages.each do |message| %>
<% to_user_id = User.find(message.to_id) %>
<% to_user_name = to_user_id.username %>
<b><p><%= to_user_name %></p></b>
<p>
<% if message.read == false %>
<b><%= link_to message.content, pm_path(to_user_id) %></b>
<% else %>
<%= link_to message.content, pm_path(to_user_id) %>
<% end %>
</p>
<% end %>
Hope I am clear and thank you in advance.