0

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?

mdmb
  • 4,833
  • 7
  • 42
  • 90
  • I think this has been asked before. Check out this answer. http://stackoverflow.com/a/5120734/2891994 – Samuel Sep 16 '16 at 22:15
  • try : `has_many :offer_items, through: :sections`. the `through` value must match another association (error explains that pretty good) – Kkulikovskis Sep 16 '16 at 22:22

1 Answers1

1

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.

SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53
  • What a stupid mistake that was. So I wasted an hour searching for tutorials but all I needed was a letter "s". Thanks a lot! – mdmb Sep 16 '16 at 22:27
  • No problem! The great thing about being stuck on this sort of stuff is that you definitely remember for the next time. :) – SteveTurczyn Sep 16 '16 at 22:31