Search code examples
ruby-on-railsruby-on-rails-3mailboxer

Maintain only one conversation over a model using Mailboxer


This is the first time I use Mailboxer. I wanna know how to configure (and if it's possible) the gem to have a Itinerary model from my reality having a conversation which messages that comes from users. (i.e): The conversation is over the Itinerary and not between users directly.

I want to are allowed to perform things like that:

itinerary.conversation.mailbox.conversations.first (It will always have one conversation)

conv = user1.itineraries.first.conversation
user1.reply_to_conversation(conv, "It's okey I want to buy the trip")
user2.reply_to_conversation(conv, "Ok. In a while the invoice will be send")

Also I want to get the users notified when a new message from the other user comes to the Itinerary conversation.

Users could be clients or agents (using single table inheritance). Both models have the directive acts_as_messageable and the Conversation model related with the Itinerary has it too.

Help is really appreciated.


Solution

  • Finally I get this working. I've marked with acts_as_messageable the involved models, Client, Agent and Itinerary. I want only mails between users (i.e Clients and Agents) and I have to return nil into the itinerary model in order to avoid the mail sending. Model Itinerary that contains a mailboxer conversation have this methods defined inside:

      def name
        return "You should add method :name in your Messageable model"
      end
    
      def mailboxer_email(object)
        #Check if an email should be sent for that object
        #if true
        return nil
        #if false
        #return nil
      end
    

    The solution to maintain and respond always over a conversation was to have logic to know if a message was written by one of the members of the conversation:

    if (itinerary.mailbox.conversations.first.nil?)
      current_user.send_message(itinerary, params[:body], "Itinerary messages")
    else
      current_user.reply_to_conversation(itinerary.mailbox.conversations.first, params[:body], "Itinerary messages")
              end 
    

    Present messages for the conversations finally is in that way:

     messages = itinerary.mailbox.conversations.first.messages.order(:created_at)
     present messages, :with => Conversations::MessageResponseEntity, success: true
    

    And thats what all. Hope it could help anyone.