ActiveRecord Association for has_one & has_many associative table
ActiveRecord Association for has_one & has_many associative table
我正在尝试建立两个模型,它们之间有关联 table。我已经这样定义了我的模型关联:
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
我在这里错过了什么?多谢!
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find
the association :homebase_address in model Homebase
您的问题出在您在 Homebase 模型中的关联中。你有 homebase_address
而不是 homebase_addresses
class Homebase < ApplicationRecord
has_many :homebase_addresses
has_many :addresses, through: :homebase_addresses
#^^^^^
end
我正在尝试建立两个模型,它们之间有关联 table。我已经这样定义了我的模型关联:
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
我在这里错过了什么?多谢!
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :homebase_address in model Homebase
您的问题出在您在 Homebase 模型中的关联中。你有 homebase_address
而不是 homebase_addresses
class Homebase < ApplicationRecord
has_many :homebase_addresses
has_many :addresses, through: :homebase_addresses
#^^^^^
end