Question

What I want to do is to get all the

My model:

class User < ActiveRecord::Base
  has_many :classes
  has_many :professors, :through=>:classes
  has_many :cars
  has_many :carmodels, :through=>:cars
end

class Professor < ActiveRecord::Base
  has_many :classes
  has_many :users, :through=>:classes
end

class Class < ActiveRecord::Base
  belongs_to :user
  belongs_to: professor
end

class Car < ActiveRecord::Base
  belongs_to :user
  belongs_to :carmodel
end

class Carmodel
  has_many :cars
  has_many :users, through=>:cars
end

what I want to do is, given a certain Car and Professor, to find all users which contain them.

for example

u1=carmodel.users
u2=professor.users
result=[]
u1.each do |us|
  if u2.include? us
    result.push us
  end
end

Of course this is just an example... I would like to keep working with ActiveRecords(avoid turning it to an array) and, of course, a more optimal solution... I can't seem to find any.

Était-ce utile?

La solution 2

Thanks for the previous answer! Here is the resulting code:

carmodel #Variable for the wanted carmodel
professor #Variable for the wanted professor
result=User.joins(:carmodels).joins(:professors).where(carmodel:{id:carmodel.id},professors:{id:professor.id})

Thanks again!

Autres conseils

You need to do something like this:

User.joins(:carmodels).joins(:professors)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top