Last active
July 9, 2018 16:17
-
-
Save hoitomt/22d3f745e2e1768a1a7992b97e5be14d to your computer and use it in GitHub Desktop.
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment