has_many通过has_one

时间:2014-09-04 16:54:11

标签: ruby-on-rails associations

我有两个模型ConversationMessage,还有一个问题ConversibleConversible有一个Conversation,而Conversation有多个Message。我想设置Conversible,以便我可以在messages上致电Conversible,它会返回Message的{​​{1}} 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的关系。

我错过了什么?

1 个答案:

答案 0 :(得分:0)

看起来你不需要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