2015-08-24 91 views
0

我有3種型號,Rails的:通過協會收到錯誤,找不到關聯

用戶,地點,項目

位置將只有1個用戶,但用戶有許多項目或位置。項目屬於用戶或位置。

class Location < ActiveRecord::Base 
    belongs_to :user 
    has_many items, through: :users 
end 

class User < ActiveRecord::Base 
    has_many :locations 
    has_many :items 
end 

class Item < ActiveRecord::Base 
    belongs_to :user 
end 

但我發現了這個錯誤:

Could not find the association :users in model Location 

我知道,我可以在定位模型添加has_many :users,但位置應該只有1個用戶。

回答

1

這應該是它:

class Location < ActiveRecord::Base 
    has_one :user 
    has_many items, through: :user 
end 

class User < ActiveRecord::Base 
    belongs_to :location 
    has_many :items 
end 

class Item < ActiveRecord::Base 
    belongs_to :user 
end 

更有意義,閱讀這樣說:

Locationhas_oneuser

Userbelongs_tolocation

Userhas_manyitems

Itembelongs_touser

Locationhas_manyitemsthrough: :user

基本上你是授權給另一模型的模型關係。因此,您無需致電location.user.items,只需執行location.items即可。

+0

但是,如果用戶有許多地方?我可以擁有belongs_to和has_many位置嗎? – hellomello

+0

我這麼認爲,你可以在用戶模型中同時擁有'belongs_to location'和'has_many locations'。給它一個鏡頭,讓我知道! 這樣做,這可能會有所幫助,並給你一些想法:http://stackoverflow.com/questions/4516416/belongs-to-and-has-many-to-the-same-model –

+0

我只是去這個錯誤。 ..'ERROR:column users.location_id does not exist LINE 1:SELECT「users」。* FROM「users」WHERE「users」。「location_id」= $ 1 ...'這是否意味着我需要添加一個' location_id'到用戶表?如果是這樣,我認爲這是錯誤的關聯,因爲,如果用戶有多個位置,那麼'user'表將存儲多個'location_id'?試圖找出這種關聯應該如何工作......我想我幾乎在那裏 – hellomello

1

因爲你說......

I know, I can add has_many :users in Location model, but location is supposed to only have 1 user.

相反的has_many :users你可以做到這一點

has_one :user