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

Adding belongs to relationship to Ruby Gem Mailboxer


I am building an e-com application and would like to implement something like a messaging system. In the application, all conversation will be related to either a Product model or an Order model. In that case, I would like to store the relating object (type + id, I supposed) to the Conversation object.

To add the fields, of course I can generate and run a migration, however, since the Model and Controller are included within the gem, how can I declare the relationship? (belongs_to :linking_object, :polymorphic) and the controller? Any idea?

Thank you.


Solution

  • Although rewriting a custom Conversation system will be the best long-term solution providing the customization requirement (Like linking with other models for instance), to save some time at the moment I have implement the link with a ConversationLink Model. I hope it would be useful for anyone in the future who are at my position.

    Model: conversation_link.rb

    class ConversationLink < ActiveRecord::Base
      belongs_to :conversation
      belongs_to :linkingObject, polymorphic: true
    end
    

    then in each models I target to link with the conversation, I just add:

    has_many :conversation_link, as: :linkingObject
    

    This will only allow you to get the related conversation from the linking object, but the coding for reverse linking can be done via functions defined in a Module.

    This is not a perfect solution, but at least I do not need to monkey patch the gem...