繁体   English   中英

has_many通过has_one

[英]has_many through a has_one

我有两种模型,“ Conversation和“ Message ,一种关注“可Conversible 一个Conversible有一个ConversationConversation有许多Message的。 我想设置“可Conversible以便可以在“可Conversible上调用messages ,它将返回“ Message ”进行Conversation 这是我到目前为止的内容:

module Conversible
  extend ActiveSupport::Concern

  included do
    has_one :conversation, as: :conversible dependent: :destroy
    has_many :messages, through: :conversation
  end
end

class Message < ActiveRecord::Base
  belongs_to :conversation
end

class Conversation < ActiveRecord::Base
  belongs_to :conversible, polymorphic: true
  has_many :messages, dependent: :destroy
end

不幸的是,这不起作用。 我可以调用conversible.messages ,但是即使conversible.conversation.messages返回其Message的关系,它也总是返回一个空的关系。

我想念什么?

看起来您不需要可Conversible模块:

class Conversation < ActiveRecord::Base
  belongs_to :conversible, polymorphic: true
  has_many :messages, dependent: :destroy
end

class Message < ActiveRecord::Base
  belongs_to :conversation
end

然后,如果您需要Conversation某种关系,可以编写:

class Post < ActiveRecord::Base
  has_many :conversations, as: :conversible
end

或者您可以尝试以下方法:

module Conversible
  extend ActiveSupport::Concern

  included 
    has_one :conversations, as: :conversible
    has_many :messages, through: :conversations
  end
end

接着:

class Post < ActiveRecord::Base
  include Conversible
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM