[英]Rails :through associations getting error, couldn't find association
I have 3 models, 我有3个型号,
Users, Location, Items 用户,位置,项目
Location would only have 1 user, but User has many items or locations. 位置将只有1个用户,但是用户有很多项目或位置。 and Items belongs to user or location.
和项属于用户或位置。
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
But I'm getting this error: 但我收到此错误:
Could not find the association :users in model Location
I know, I can add has_many :users
in Location model, but location is supposed to only have 1 user. 我知道,我可以在Location模型中添加
has_many :users
,但是location应该只有1个用户。
This should be it: 应该是这样:
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
To make more sense, read it this way: 为了更有意义,请按以下方式阅读:
Location
has_one
user
Location
has_one
user
User
belongs_to
location
User
belongs_to
location
User
has_many
items
User
has_many
items
Item
belongs_to
user
Item
belongs_to
user
Location
has_many
items
, through: :user
Location
has_many
items
, through: :user
Essentially you are delegating a model relationship to another model. 本质上,您是将一个模型关系委派给另一个模型。 So instead of having to call
location.user.items
you can just do location.items
. 因此,您不必调用
location.user.items
即可执行location.items
。
because you say ... 因为你说 ...
I know, I can add has_many :users in Location model, but location is supposed to only have 1 user.
我知道,我可以在Location模型中添加has_many:users,但是location应该只有1个用户。
Instead of has_many :users
you could do this 代替
has_many :users
你可以这样做
has_one :user
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.