How to query a model based on attribute of another model which belongs to the first model?

两盒软妹~` 提交于 2019-11-26 19:07:16

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 # 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

Similar questions:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!