我有两个模型Conversation
和Message
,还有一个问题Conversible
。 Conversible
有一个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
的关系。
我错过了什么?
答案 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