11

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')
Alexander Popov
  • 23,073
  • 19
  • 91
  • 130

1 Answers1

20

You can do as following:

Person.includes(:vehicles).where(vehicles: { vehicle_type: 'auto' })
Person.includes(:vehicles).where(vehicles: { vehicle_type: 'motorcycle' })

Be careful 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

Alternatively, the gem activerecord_where_assoc can achieve this (and much more):

Person.where_assoc_exists(:vehicles, vehicle_type: 'auto')

Similar questions:

Jim U
  • 3,318
  • 1
  • 14
  • 24
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
  • Thank you for the answer, but I need a clarification. You say: "the `includes/joins` methods use the name defined in the model", but in the second example you write `Post.includes(:user)`. Don't you mean that pluralization in `includes/joins` depends on the relationship of the two models? – Alexander Popov May 13 '14 at 15:01
  • 1
    @AlexPopov The pluralization in `includes/joins` depends on the name of the association defined in the model. If it was defined as `belongs_to :owner, class_name: 'User'`, you would have to use the relation's name: `.includes(:owner)` – MrYoshiji May 13 '14 at 15:05