If I have a model Person
, which has_many
Vehicles
and each Vehicle
can be of type car
or motorcycle
You can do as following:
Person.includes(:vehicles).where(vehicles: { vehicle_type: 'auto' })
Person.includes(:vehicles).where(vehicles: { vehicle_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
Alternatively, the gem activerecord_where_assoc can achieve this (and much more):
Person.where_assoc_exists(:vehicles, vehicle_type: 'auto')
Similar questions: