ActiveRecord关联has_one&has_many关联表
问题描述:
我试图设置两个模型,并在它们之间建立关联表。我定义我的模型协会评为例如:ActiveRecord关联has_one&has_many关联表
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
我的情况下创建OK:
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
我在这里错过了什么?感谢堆!
答
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :homebase_address in model Homebase
您的问题是在固定课室模型的相关项目。你有而不是homebase_addresses
class Homebase < ApplicationRecord
has_many :homebase_addresses
has_many :addresses, through: :homebase_addresses
#^^^^^
end
谢谢你修好了! –