带有has_one的STI通过不工作

时间:2013-09-18 09:47:44

标签: ruby-on-rails ruby-on-rails-4

我的模特:

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加入。有可能吗?

1 个答案:

答案 0 :(得分:2)

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

因为Content有很多content_listings,每个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