如何查询基于另一个模型的属性的模型属于第一种模式?模型、第一种、属性、模式

2023-09-08 15:42:14 作者:不努力,未来永远是个梦

如果我有一个模型,其中的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
 
精彩推荐
图片推荐