Rails 5 Query when using both single and multiple association relationships

171 Views Asked by At

I have a rails app with the following setup:

class Organization < ApplicationRecord
    has_many :user_orgs
    has_many :users, :through => :user_orgs
end

class UserOrg < ApplicationRecord
    #  organization_id      :integer
    #  user_id :integer
    belongs_to :organization
    belongs_to :user
end

class User < ApplicationRecord
    #  car_id :integer
    has_many :user_orgs
    has_many :organizations, :through => :user_orgs
    belongs_to :car
end

class Car < ApplicationRecord
    #  brand :string
    has_many :users
end

What I am trying to do is to write a Rails 5 query so that it returns all organizations where a certain car attribute is set, i.e. return all organizations where there is a user who has a car with a given brand.

How can I join the Car class on the Organization when doing the query? Currently, I search for organizations based on User criteria by doing the following:

Organization.joins(:users).where("users.name = ?", name)

But I want to be able to add car criteria to the query as well.

1

There are 1 best solutions below

5
Milind On

How about using this-

###add this scope in Organisation model that has - has_many :users
scope :get_users_by_carBrand, -> (brand) { includes(:cars).where(:cars=> {:name => brand} }

###this is the select query 
Organization.includes(:users).get_users_by_carBrand("BMW")