简体   繁体   English

has_many通过has_one

[英]has_many through a has_one

I have two models, Conversation and Message , and one concern Conversible . 我有两种模型,“ Conversation和“ Message ,一种关注“可Conversible A Conversible has one Conversation and a Conversation has many Message 's. 一个Conversible有一个ConversationConversation有许多Message的。 I'd like to set up Conversible so I can call messages on my Conversible and it will return the Message 's for its Conversation . 我想设置“可Conversible以便可以在“可Conversible上调用messages ,它将返回“ Message ”进行Conversation Here's what I have so far: 这是我到目前为止的内容:

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

Unfortunately, this doesn't work. 不幸的是,这不起作用。 I can call conversible.messages , but it always returns an empty relation, even when conversible.conversation.messages returns a relation with its Message 's. 我可以调用conversible.messages ,但是即使conversible.conversation.messages返回其Message的关系,它也总是返回一个空的关系。

What am I missing? 我想念什么?

looks like you don't need Conversible module: 看起来您不需要可Conversible模块:

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

class Message < ActiveRecord::Base
  belongs_to :conversation
end

and then if you need some relation for Conversation you could write: 然后,如果您需要Conversation某种关系,可以编写:

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

or you could try something like: 或者您可以尝试以下方法:

module Conversible
  extend ActiveSupport::Concern

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

and then: 接着:

class Post < ActiveRecord::Base
  include Conversible
end

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

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