我有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個用戶。
但是,如果用戶有許多地方?我可以擁有belongs_to和has_many位置嗎? – hellomello
我這麼認爲,你可以在用戶模型中同時擁有'belongs_to location'和'has_many locations'。給它一個鏡頭,讓我知道! 這樣做,這可能會有所幫助,並給你一些想法:http://stackoverflow.com/questions/4516416/belongs-to-and-has-many-to-the-same-model –
我只是去這個錯誤。 ..'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