ruby-on-rails - STI 与 has_one 通过不工作

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

最佳答案

这里不能设置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/

相关文章:

ruby-on-rails - 在 Rails 测试套件中使用工厂的优点和缺点?

ruby-on-rails - 赫罗库:! [rejected] master -> master(非快进)

ruby-on-rails - 如何在生产 rails 4 中提供指纹 css 路径

ruby-on-rails - Link_to 不工作?

ruby-on-rails - Railscast 中的建筑测量 Rails 5

ruby-on-rails - 使用 ActiveJob 时是否仍只传递对象 ID?

javascript - Rails 4.1 has_many.js 错误

javascript - jQuery 插件 photopile 无法工作,但很简单,我可能做错了什么吗?

ruby-on-rails - Rails 中的复选框是如何工作的?

ruby-on-rails - Ruby on Rails View 未拉入 application.html.erb 布局