3

我的模型:

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 的相关列表,然后通过我的 ContentListing 加入。可能吗?

4

1 回答 1

2

这里不能设置has_one 关系'related_group_list' 可以设置has_many。

因为 Content 有很多 content_listing,每个 content_listing 都有一个 related_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
于 2013-09-18T11:27:54.773 回答