![](/img/trans.png)
[英]has_one :through and has_many :through in the same association
[英]has_many through a has_one
我有两种模型,“ Conversation
和“ Message
,一种关注“可Conversible
。 一个Conversible
有一个Conversation
和Conversation
有许多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.