![](/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.