Show username on Mailboxer inbox in Rails

980 views Asked by At

I'm using the Mailboxer (https://github.com/ging/mailboxer) gem in my Rails app to handle private messages between users. As per the documentation, I'm using = render mailbox.inbox to show a list of all conversations (messages) for the logged-in user. However, the method only outputs the subject of the message. I need to show the sender of the message along with the subject. How can I edit this output so that the sender name is displayed?

The SQL table shows that the sender name is not stored in the conversations table, but on the notifications table via notifications_on_conversation_id (one to many). I tried to use <%= conversation.notifications.sender_id %> but I got the following error:

NoMethodError in Conversations#index
undefined method `notifications' for nil:NilClass

What can I add to the conversation controller and view in order to display the conversation's user and subject?

Thanks!

Conversations controller:

class ConversationsController < ApplicationController
  before_filter :authenticate_user!
  helper_method :mailbox, :conversation

  def create
    recipient_emails = conversation_params(:recipients).split(',')
    recipients = User.where(email: recipient_emails).all

    conversation = current_user.
      send_message(recipients, *conversation_params(:body, :subject)).conversation

    redirect_to conversation
  end

  def reply
    current_user.reply_to_conversation(conversation, *message_params(:body, :subject))
    redirect_to conversation
  end

  def trash
    conversation.move_to_trash(current_user)
    redirect_to :conversations
  end

  def untrash
    conversation.untrash(current_user)
    redirect_to :conversations
  end

  private

  def mailbox
    @mailbox ||= current_user.mailbox
  end

  def conversation
    @conversation ||= mailbox.conversations.find(params[:id])
  end

  def conversation_params(*keys)
    fetch_params(:conversation, *keys)
  end

  def message_params(*keys)
    fetch_params(:message, *keys)
  end

  def fetch_params(key, *subkeys)
    params[key].instance_eval do
      case subkeys.size
      when 0 then self
      when 1 then self[subkeys.first]
      else subkeys.map{|k| self[k] }
      end
    end
  end
end
2

There are 2 answers

0
user2934685 On BEST ANSWER

sender_id is available using receipt.notification.sender_id and .sender_type

for any conversation you can retrieve the receipts using: @receipts = conversation.receipts_for

0
zamuro On

I ran on the same issue at some point and my solution was something like this: accessing current_user in mailboxer mailer notification