2016-09-16 104 views
0

我有一个名为发售的has_many通过 - 访问属性

class Offer < ApplicationRecord 
    has_many :sections 
    has_many :offer_items, through: :section 
end 

class Section < ApplicationRecord 
    belongs_to :offer 
    has_many :offer_items 
end 

class OfferItem < ApplicationRecord 
    belongs_to :section 
    belongs_to :offer 
end 

模型播种这样的数据库后:

offer = Offer.create(name: "Offer A") 
section = offer.sections.create(name: "Section A") 
item = section.offer_items.create(name: "Item A") 

项目将不会被创建,如果我想访问offer_items像Offer.first.offer_items它给我一个错误:

ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :section in model Offer 

我也可以看到OfferItem.attribute_names返回每个属性,但没有offer_id,所以它看起来像其他belongs_to不起作用。 这是怎么回事?

+0

我认为这已经被问过。看看这个答案。 http://stackoverflow.com/a/5120734/2891994 – Samuel

+0

尝试:'has_many:offer_items,through::sections'。 “通过”值必须与另一个关联相匹配(错误解释了很好) – Kkulikovskis

回答

1

这不是

has_many :offer_items, through: :section 

这是

has_many :offer_items, through: :sections 

你没有:section关联,您有:sections关联。

+0

这是多么愚蠢的错误。所以我浪费了一个小时寻找教程,但我只需要一个字母“s”。非常感谢! – Ancinek

+0

没问题!被困在这种东西上的伟大之处在于,你一定记得下一次。 :) – SteveTurczyn