2015-08-24 56 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