我的模型:
Content
RelatedList
RelatedGroupList < RelatedList # STI
ContentListing
在内容上,我有
has_many :content_listings # all the below relations are joined using this which has content_id and related_list_id columns
has_one :related_group_list, through: :content_listings, source: 'RelatedList'
has_one :related_people_list, through: :content_listings, source: 'RelatedList'
has_one :related_website_list, through: :content_listings, source: 'RelatedList'
基本上,我想获取“content.related_group_list”,它应该获取相关组列表的记录。
但是,我得到这个错误:
ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :RelatedList in model ContentListing. Try 'has_many :related_group_list, :through => :content_listings, :source => <name>'. Is it one of :content or :related_list?
我用这一行检查了我的 ContentListing 模型:
belongs_to :related_list
我的 ContentListing 模型中缺少什么?
编辑 1:
在我发布这个问题之后,我阅读了一些关于协会的其他文章并更改了行
has_one :related_group_list, through: :content_listings, source: 'RelatedList'
到
has_one :related_group_list, through: :content_listings, source: :related_list
它现在给我以下错误:
ActiveRecord::HasOneThroughCantAssociateThroughCollection: Cannot have a has_one :through association 'Content#related_group_list' where the :through association 'Content#content_listings' is a collection. Specify a has_one or belongs_to association in the :through option instead.
我要我的
has_one :related_group_list, through: :content_listings, source: :related_list
自动仅获取类型为 RelatedGroupList 的 related_list,然后通过我的 ContentListing 加入。可能吗?
最佳答案
这里不能设置has_one关系 'related_group_list' 可以设置has_many。
因为Content有很多个content_listing,每个content_listing都有一个related_list。 这意味着每个内容可以有多个 related_group_list 而不是一个。
所以如果你想获取 content.related_group_lists 那么你可以这样做
在 ContentListing 模型中——:
class ContentListing < ActiveRecord::Base
belongs_to :related_list
belongs_to :related_group_list, class_name: 'RelatedList',
foreign_key: 'related_list_id'
belongs_to :content
end
在内容模型中-:
class Content < ActiveRecord::Base
has_many :content_listings
has_many :related_lists, through: :content_listings
has_many :related_group_lists, through: :content_listings
end
关于ruby-on-rails - STI 与 has_one 通过不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18868969/