如何在 Ruby on Rails 中访问 an:m 关系中的引用表?
我有一个像这样的数据库:
users
-id
user_cars
-user_id
-car_id
cars
-id
-model
-color
所以一个用户可以拥有多辆汽车,有关汽车的详细信息位于一个大汽车表中。我还创建了具有关系的模型。
class User
has_many :user_cars
class User_car
belongs_to :user
belongs_to :cars
class Car
has_many :user_cars
现在我想访问一个用户的所有汽车的信息。我的第一个方法是从汽车表中获取至少一个信息(即颜色)。
我尝试了这个,只是作为访问中间表的示例:
@user_id = current_user.user_cars.find(1).user_id
有效!但是当我尝试访问 cars 表时,我总是收到错误。
@color = current_user.user_cars.cars.find(1).color
undefined method `cars' for #<ActiveRecord::Relation:0xaf92e8c>
所以我认为我做了一些简单的非常错误的事情......
当我知道如何访问第三个表时,我必须以这种方式进行,我只为用户获取结果,而不仅仅是第一个条目,也许你们也可以帮助我。谢谢!
I have got a Database like this:
users
-id
user_cars
-user_id
-car_id
cars
-id
-model
-color
So a user can have multiple cars, and detailed information about the cars are in a big cars table. I also created the models with the relationships.
class User
has_many :user_cars
class User_car
belongs_to :user
belongs_to :cars
class Car
has_many :user_cars
Now I want to access the information for all the cars for one user. My first approach would be to get at least one information (i.e. color) from the cars table.
I tried this one, just as an example for accessing the middle table:
@user_id = current_user.user_cars.find(1).user_id
works! But when I try to access the cars table I always get an error.
@color = current_user.user_cars.cars.find(1).color
undefined method `cars' for #<ActiveRecord::Relation:0xaf92e8c>
So I think Im doin something easy very wrong...
When I know how to get access to the third table, I have to do it in that fashion, that I only get results for the user and not just only the first entry, maybe you guys can help me with that aswell. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
顺便说一句,您的示例中的问题是belongs_to应该是单数。另外,你的订单是错误的。
您应该重写它以使用 has_many through 关联:
您可以然后通过执行以下操作来访问汽车:
并通过执行以下操作来访问颜色:
编辑
经过一些调试,事实证明汽车模型具有类属性。 Class 是 ruby 中的保留字。命名你的属性时要小心!
The issue in your example by the way is that belongs_to should be singular. Also, your order was wrong.
You should rewrite this to use a has_many through association:
You can then access the cars by doing:
And the color by doing:
EDIT
After some debugging, it turns out that the Car model has a class property. Class is a reserved word in ruby. Be careful with naming your attributes!
没有 has_many :through 关联:
使用它们:
http://guides.rubyonrails。 org/association_basics.html#the-has_many-through-association
has_and_belongs_to_many
的 users_cars)有关这些的详细信息在上面的链接中。
Without has_many :through associations:
With them:
http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association
has_and_belongs_to_many
)Details on those are in the link above.