Search code examples
ruby-on-railsruby-on-rails-3loopsprivate-messaging

Rails Mailboxer/messaging -- Only return non-empty arrays


Im using the mailboxer gem to build a private messaging system.

I want to loop over my user list, and next to each users name, provide a link to open a preexisting conversation if it exists, or create a new one if no conversation does exist. (So users would only be able to have 1 conversation with another user, rather than an email like system).

<% @users.each do |u| %>
  <%= link_to u.name, u %>
  <% @mailbox.conversations.each do |c| %>
    <% if c.receipts.where(:receiver_id => user).present? %>
     true
    <% else %>
     false
    <% end %>
  <% end %>
<% end %>

so "true" would be the link to reopen the conversation and "false" would be a button for a new conversation.

but if a user has 4 conversations and 1 with a given user, it would return true false false false. so 1 continue button and 3 create new. so essentially, i need the entire thing to return either true or false


Solution

  • if anyone is interested, this is a more elegant solution. just in the controller. then all links are the same, and it will open message if it exists. filtering by Conversation.participant(a).participant(b) was the key

    def new
      @recipient = User.find(params[:recipient])
      @ongoing_conversation = Conversation.participant(current_user).participant(@recipient)
    
      respond_to do |format|
        format.html { redirect_to root_path }
        if @ongoing_conversation.present?
          format.js { redirect_to mailbox.conversations.find(@ongoing_conversation) }
        else
          format.js
        end
      end
    end