简体   繁体   中英

has_many through a has_one

I have two models, Conversation and Message , and one concern Conversible . A Conversible has one Conversation and a Conversation has many Message 's. 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 . 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.

What am I missing?

looks like you don't need Conversible module:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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