ActiveRecord Association for has_one& has_many关联表

时间:2016-08-23 10:30:21

标签: ruby-on-rails activerecord associations models

我试图设置两个模型,它们之间有一个关联表。我已经定义了我的模型关联:

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

我的协会:

 class HomebaseAddress < ApplicationRecord
   belongs_to :homebase
   belongs_to :address
 end

我的实例创建正常:

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

然而,

homebase.addresses

给出以下错误:

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

我在这里缺少什么?谢谢你!

1 个答案:

答案 0 :(得分:3)

  

ActiveRecord :: HasManyThroughAssociationNotFoundError:找不到   关联:homebase中的homebase_address

您的问题出在 Homebase 模型中的关联中。您有homebase_address而不是homebase_addresses

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