4

I want to extend Conversation model, so that i can use an association with it. I have done it by creating a file named 'conversation.rb' in app/models directory in this way:

Mailboxer::Conversation.class_eval do
  belongs_to :device, class_name: "Device", foreign_key: 'device_id'
end

I have also added a column named 'device_id' in conversations table.

But when i tries:

Conversation.last.device

It say:

NoMethodError: undefined method `device' for #<Mailboxer::Conversation:0x007fe83e6ae7c0>
Aman Garg
  • 4,198
  • 2
  • 21
  • 29

2 Answers2

3

The problem is that app/models/conversation.rb won't be loaded if Mailboxer::Conversation is called. I made this work for me by moving your code to config/initializers/mailboxer.rb. Additionally, I wrapped the code in Rails.application.config.to_prepare since in development mode this code have to be re-executed on reload (see Monkey patching Devise (or any Rails gem)):

Mailboxer.setup do |config|
  [...]
end

Rails.application.config.to_prepare do
  Mailboxer::Conversation.class_eval do
    belongs_to :device
  end
end

This way, something like current_user.mailbox.conversations.first.device should be possible.

Community
  • 1
  • 1
lacco
  • 882
  • 1
  • 10
  • 24
  • Thanks, lacco :) I'm using Rails 5.0.2 and it works fine without wrapping the code in `Rails.application.config.to_prepare` block. – Ammar Shah Mar 01 '18 at 17:47
1

You can try inherit from it

class Conversation < Mailboxer::Conversation
  belongs_to :device, class_name: "Device", foreign_key: 'device_id'
end
z3ple
  • 348
  • 1
  • 3
  • 11
  • I am pretty sure that this won't work out of the box since Mailboxer will still use the ```Mailboxer::Conversation``` class. If this is the preferred solution, something like ```current_user.mailbox.conversations.first.becomes(::Conversation)``` might help. – lacco Feb 26 '15 at 07:45