如果我有一个模型人
,其中的has_many
车
每个车
可以是类型车
或摩托车
,我怎么可以查询所有的人,谁拥有汽车和所有的人,谁拥有摩托车?
我不认为这是正确的:
Person.joins(:辆)。凡(汽车类型:自动)
Person.joins(:辆)。凡(汽车类型:'摩托车')
解决方案
您可以执行如下:
Person.includes(:辆)。凡(车辆:{类型:'自动'})
Person.includes(:辆)。凡(车辆:{类型:'摩托车'})
要当心与 .joins
和 .includes
:
#考虑这些模型
帖子
belongs_to的:用户
#^ ^
用户
的has_many:帖子
#^
#在`包括/ joins`方法使用在模型中定义的名称:
User.includes(:帖子)。凡(帖子:{标题:博比表'})
#^ ^
#但是`where`采用多元化的版本(表的名称):
Post.includes(:用户)。凡(网友:{名称:博比})
#^ ^ ^ ^
有一个很微妙的:
发布
belongs_to的:作者,将class_name:用户
用户
的has_many:帖子
Post.includes(:作者)。凡(网友:{名称:'约翰'})
类似的问题:
association命名未发现可能拼错的问题,在轨协会 Rails与活动记录查询协会'存在' Rails 3,HAS_ONE /的has_many与拉姆达条件 Rails 4范围找父母没有子女 Join与活跃记录多个表 Rails:查找所有用户的关系已经指定属性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')
解决方案
You can do as following:
Person.includes(:vehicles).where(vehicles: { type: 'auto' })
Person.includes(:vehicles).where(vehicles: { type: 'motorcycle' })
Be carefull with .joins
and .includes
:
# consider these models
Post
belongs_to :user
#^^
User
has_many :posts
#^
# the `includes/joins` methods use the name defined in the model :
User.includes(:posts).where(posts: { title: 'Bobby Table' })
#^ ^
# but the `where` uses the pluralized version (table's name) :
Post.includes(:user).where(users: { name: 'Bobby' })
#^^^ ^
A tricky one:
Post
belongs_to :author, class_name: 'User'
User
has_many :posts
Post.includes(:author).where(users: { name: 'John' })
Similar questions:
association named not found perhaps misspelled issue in rails association Rails active record querying association with 'exists' Rails 3, has_one / has_many with lambda condition Rails 4 scope to find parents with no children Join multiple tables with active records Rails: Finding all Users whose relationship has a specified attribute下一篇:加入与活跃记录的多个表多个、活跃