ruby-on-railsruby-on-rails-4activerecordrails-activerecordruby-on-rails-4.2

Rails: OR where condition on association


I have a model called Facility. It has_many :addresses. The Address model has_one :city.

Now I want to run a condition:

I have tried the first condition but I am unable to combine an OR for it.

This gets all facilities that do not have an address model associated to it

Facility.includes(:addresses).where( :addresses => {:facility_id => nil})

Some error tries are:

Facility.includes(:addresses).where( :addresses => ({:facility_id => nil}).or({:city_id => nil}) );
Facility.includes(:addresses).where( :addresses => ({:facility_id => nil}).or(:address => {:city_id => nil}) )

Solution

  • Try the following:

    Facility.includes(:addresses)
            .where('addresses.facility_id is null or addresses.city_id is null')
            .references(:addresses)
    

    You can also find interesting this post, concerning possible implementations of the or condition in the activerecord queries.