如何根据属于第一个模型的另一个模型的属性查询模型? [英] How to query a model based on attribute of another model which belongs to the first model?
本文介绍了如何根据属于第一个模型的另一个模型的属性查询模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个模型 Person
,它的 has_many
Vehicles
和每个 Vehicle
可以是 car
或 motorcycle
,如何查询所有有车的人和所有有摩托车的人?
If I have a model Person
, which has_many
Vehicles
and each Vehicle
can be of type car
or motorcycle
, how can I query for all persons, who have cars and all persons, who have motorcycles?
我不认为这些是正确的:
I don't think these are correct:
Person.joins(:vehicles).where(vehicle_type: 'auto')
Person.joins(:vehicles).where(vehicle_type: 'motorcycle')
推荐答案
您可以执行以下操作:
Person.includes(:vehicles).where(vehicles: { vehicle_type: 'auto' })
Person.includes(:vehicles).where(vehicles: { vehicle_type: 'motorcycle' })
小心 .joins
和 .includes
:
# consider these models
Post # table name is posts
belongs_to :user
#^^
User # table name is users
has_many :posts
#^
# the `includes/joins` methods use the relation name defined in the model:
User.includes(:posts).where(posts: { title: 'Bobby Table' })
#^ ^
# but the `where` uses the exact table name:
Post.includes(:user).where(users: { name: 'Bobby' })
#^^^ ^
一个棘手的问题:
A tricky one:
Post
belongs_to :author, class_name: 'User'
User # table named users
has_many :posts
Post.includes(:author).where(users: { name: 'John' })
# because table is named users
或者,gem activerecord_where_assoc 可以实现这一点(以及更多):
Alternatively, the gem activerecord_where_assoc can achieve this (and much more):
Person.where_assoc_exists(:vehicles, vehicle_type: 'auto')
类似问题:
- 可能未找到已命名的关联Rails 关联中的拼写错误问题
- Rails 活动记录查询与存在"的关联一个>
- Rails 3, has_one/has_many with拉姆达条件
- Rails 4 范围来查找父母没有孩子
- 加入多个具有活动记录的表
- Rails:查找所有用户其关系具有指定属性
这篇关于如何根据属于第一个模型的另一个模型的属性查询模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文