簡體   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