# Retrieve the user
user = User.find(params[:user_id])
  
# Get all of the messages for the user and order so that the most recent message is first
raw_messages = Message.where("sender_user_id=? or receiver_user_id=?", user.id, user.id).order("created_at DESC")

# Our goal is to make a hash that looks like this:
# {
#   other_party_1: [msg1, msg2, msg3],
#   other_party_2: [msg7, msg8, msg9],
#   ...
# }

# To do that we need to group the messages by user id:
# Group those messages by the id of the other user (think of inject as a way to turn an array into a hash)
@user_messages = raw_messages.inject(Hash.new) do |h, msg|
  # Get the other party id
  other_party_id = if msg.sender_user_id != user.id
    msg.sender_user_id
  else
    msg.receiver_user_id
  end
  
  # If the other_party_id is already in the hash, then add it to the existing array
  # Else create a new array and assign it to the hash key
  if h[other_party_id]
    h[other_party_id] << msg
  else
    h[other_party_id] = [msg]
  end
end

# Now you have a grouped list of messages that looks like what we want.

# In your view
<% @user_messages.do |other_party_id ,msg_array| %>
  other_party = User.find(other_party_id)
  <h4><%= other_party.handle %><h4>
  <% msg_array.each do |msg| %>
    # Display your message here - probably just a snippet like IOS does
  <% end %>
  # Instead of the array you may want to just display a snippet of the most recent message
  <p><%= msg_array.first.body %></p>
<% end %>