【问题标题】:Extend Conversation model in Mailboxer gem在 Mailboxer gem 中扩展对话模型
【发布时间】:2014-08-30 10:51:57
【问题描述】:

我想扩展对话模型,这样我就可以使用它的关联。我通过这种方式在 app/models 目录中创建了一个名为“conversation.rb”的文件:

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

我还在对话表中添加了一个名为“device_id”的列。

但是当我尝试时:

Conversation.last.device

它说:

NoMethodError: undefined method `device' for #<Mailboxer::Conversation:0x007fe83e6ae7c0>

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 mailboxer


    【解决方案1】:

    问题是如果Mailboxer::Conversation 被调用,app/models/conversation.rb 将不会被加载。我通过将您的代码移至 config/initializers/mailboxer.rb 为我完成了这项工作。此外,我将代码包装在 Rails.application.config.to_prepare 中,因为在开发模式下,此代码必须在重新加载时重新执行(参见 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
    

    这样,current_user.mailbox.conversations.first.device 这样的东西应该是可能的。

    【讨论】:

    • 谢谢,lacco :) 我使用的是 Rails 5.0.2,它可以正常工作,无需将代码包装在 Rails.application.config.to_prepare 块中。
    【解决方案2】:

    你可以尝试继承它

    class Conversation < Mailboxer::Conversation
      belongs_to :device, class_name: "Device", foreign_key: 'device_id'
    end
    

    【讨论】:

    • 我很确定这不会开箱即用,因为 Mailboxer 仍将使用 Mailboxer::Conversation 类。如果这是首选解决方案,current_user.mailbox.conversations.first.becomes(::Conversation) 之类的内容可能会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多