How to search in Active Record with the condition A + B

Solution for How to search in Active Record with the condition A + B
is Given Below:

I would like to specify each condition for Maintenance and Ability associated with a Person and retrieve each of them.

Normally, the query would be to retrieve the records that contain the two conditions, Person.maintenances and Person.abilities.

A = Person.maintenances.where(~~~~)
B = Person.abilities.where(~~~)

I want to get all of the above in a single query as a Person.
(What I want = A + B in a single query)

Also, I don’t want to have the N+1 problem, but I would like to know how to prevent the query from being issued because the conditions of Person.maintenances and Person.abilities are separated.

class Person << ApplicationRecord
  has_many :maintenances
  has_many :abilities

class Maintenance << ApplicationRecord
  belongs_to :person

class Ability << ApplicationRecord
  belongs_to :person

※I’m using MySQL


A simple join should do the trick:

Person.joins(:maintenance).where(maintenances: {status: 0, example: "yes"}).joins(:ability).where(abilities: {........})

Or something like this, which should create the same result

Person.where(maintenances: Maintenance.where(person: self, ......), abilities: Ability.where(person: self, ......))