mdmb
mdmb

Reputation: 5283

has_many through - accessing attributes

I have a model called 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

After seeding the database like this:

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

The item is not created and if I want to access offer_items like Offer.first.offer_items it gets me an error:

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

I can also see that OfferItem.attribute_names returns every attribute but no offer_id so it seems like the other belongs_to is not working. What is going on here?

Upvotes: 0

Views: 205

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

It's not

has_many :offer_items, through: :section

It's

has_many :offer_items, through: :sections

You don't have a :section association, you have a :sections association.

Upvotes: 1

Related Questions