0

I have an array of "names" and I would like to display the current user's name ONLY IF there it is the only name in the array. If there are other names in the array, I don't want to show the current user's name.

Currently, I am listing the names and excluding the current user's name, but don't want to exclude the current user's name if it is the only one in the array. I hope I explained that okay.

My code now:

module ConversationsHelper

def other_user_names(conversation)

    users = []
    conversation.messages.map(&:receipts).each do |receipts|
        users << receipts.select do |receipt|
            receipt.receiver != current_user
        end.map(&:receiver)

    end
    users.flatten.uniq.map(&:name).join ', '

end
end
1
  • 1
    First collect all receivers, then check against current user. Commented Jun 26, 2014 at 7:41

1 Answer 1

5

This should work:

def other_user_names(conversation)
  # get all users (no duplicates)
  users = conversation.messages.map(&:receipts).map(&:receiver).uniq

  # remove current user if there are more than 1 users
  users.delete(current_user) if users.many?

  # return names
  users.map(&:name).join(', ')
end

I would move the first line into a Conversation#users method.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the help, much appreciated. I'm confused as to what you mean by moving the first line.. Are you saying move the helper into the controller, or take the other_user_names and put that in the conversations controller? Thanks again.
When I replaced my method with yours (still in the helper), I get this error: undefined method `receiver' for #<Mailboxer::Receipt::ActiveRecord_Associations_CollectionProxy:0x007fc1b9fdf9f8>
@user2756384 Not the helper itself, but the helper's first line, i.e. `users = conversation.messages.map(&:receipts).map(&:receiver).uniq
Could you post your associations from Conversation to User, please?
I'm using the mailboxer Gem. I'm not exactly sure how the assocations work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.