2016-08-23 213 views
2

我試圖設置兩個模型,並在它們之間建立關聯表。我定義我的模型協會評爲例如: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 

我在這裏錯過了什麼?感謝堆!

回答

3

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 
+1

謝謝你修好了! –