has_many through - 访问属性

时间:2016-09-16 22:07:40

标签: ruby-on-rails

我有一个名为Offer

的模型
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不起作用。 这是怎么回事?

1 个答案:

答案 0 :(得分:1)

不是

<table border="1">
  <tr>
    <td rowspan="2">
      <img class="image" src="Posters/suicidesquad-poster1.jpg">
    </td>
    <td rowspan="2">Suicide Squad</td>
    <td rowspan="2">PG-13</td>
    <td Rowspan="2">2 Hour(s) 3 Minutes</td>
    <td>Row One</td>
    <td rowspan="2">CC, DV</td>
  </tr>
  <tr>
    <td>Row Two</td>
  </tr>
</table>

这是

has_many :offer_items, through: :section

您没有has_many :offer_items, through: :sections 关联,您有:section关联。