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

佐手、 提交于 2019-12-17 04:34:22

问题


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')

回答1:


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:

  • 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


来源:https://stackoverflow.com/questions/23633301/how-to-query-a-model-based-on-attribute-of-another-model-which-belongs-to-the-fi

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