加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何根据属于第一个模型的另一个模型的属性查

发布时间:2020-12-16 21:35:14 所属栏目:百科 来源:网络整理
导读:如果我有一个模型人员,其中有多辆车,每辆车可以是汽车或摩托车,我怎样才能查询所有拥有汽车的人和所有拥有摩托车的人? 我不认为这些是正确的: Person.joins(:vehicles).where(vehicle_type: 'auto')Person.joins(:vehicles).where(vehicle_type: 'motorcyc
如果我有一个模型人员,其中有多辆车,每辆车可以是汽车或摩托车,我怎样才能查询所有拥有汽车的人和所有拥有摩托车的人?

我不认为这些是正确的:

Person.joins(:vehicles).where(vehicle_type: 'auto')
Person.joins(:vehicles).where(vehicle_type: 'motorcycle')

解决方法

您可以执行以下操作:
Person.includes(:vehicles).where(vehicles: { type: 'auto' })
Person.includes(:vehicles).where(vehicles: { 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' })
                #^^^           ^

一个棘手的问题:

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

类似的问题:

> 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读