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>
4

2 回答 2

3

问题是如果被调用app/models/conversation.rb则不会加载。Mailboxer::Conversation我通过将您的代码移至config/initializers/mailboxer.rb. 此外,我将代码包装在其中,Rails.application.config.to_prepare因为在开发模式下,必须在重新加载时重新执行此代码(请参阅Monkey patching Devise(或任何 Rails gem)):

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

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

这样,类似的事情current_user.mailbox.conversations.first.device应该是可能的。

于 2015-02-26T07:48:28.600 回答
1

你可以尝试继承它

class Conversation < Mailboxer::Conversation
  belongs_to :device, class_name: "Device", foreign_key: 'device_id'
end
于 2014-07-30T15:47:53.180 回答