Search code examples
ruby-on-railsactiverecordassociationsmodels

ActiveRecord Association for has_one & has_many associative table


I'm trying to set up two models, with an associative table between them. I have defined my model associations as such:

class Homebase < ApplicationRecord
  has_many :homebase_addresses
  has_many :addresses, through: :homebase_address
end

class Address < ApplicationRecord
  has_one :homebase_address
  has_one :homebase, through: :homebase_address
end

And my association:

 class HomebaseAddress < ApplicationRecord
   belongs_to :homebase
   belongs_to :address
 end

My instances create OK:

homebase = Homebase.create
address = Address.create
homebase_address = HomebaseAddress.create(homebase: homebase, address: address)

However,

homebase.addresses

gives the following error:

ActiveRecord::HasManyThroughAssociationNotFoundError:
       Could not find the association :homebase_address in model Homebase

What am I missing here? Thanks heaps!


Solution

  • ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :homebase_address in model Homebase

    Your problem is in your associations in Homebase model. You have homebase_address instead of homebase_addresses

    class Homebase < ApplicationRecord
      has_many :homebase_addresses
      has_many :addresses, through: :homebase_addresses
                                              #^^^^^
    end