Vyacheslav Loginov
Vyacheslav Loginov

Reputation: 3216

Active record without JOIN

I have

class Autosalon < ActiveRecord::Base
  has_many :autos
end

class Auto < ActiveRecord::Base
  belongs_to :autosalon
end

autosalon has flag active=1 and date of registration, auto has flag active=1

How get all autos with active flag in autosalons with active flag without JOIN?

Upvotes: 0

Views: 123

Answers (2)

Chris Cherry
Chris Cherry

Reputation: 28554

Something like this should do it:

active_autosalons = Autosalon.where(:active => 1)
active_autos = Autos.where(:autosalon_id => active_autosalons.map(&:id)).where(:active => 1)

Get the list of 'active' Autosalons first, then filter Autos by the Autosalon ids and the active column.

Upvotes: 1

Dylan Markow
Dylan Markow

Reputation: 124419

Without any joins/includes, you could use a SQL in query:

Auto.where(:active => 1).where("autosalon_id in (select id from autosalons where active=1)")

Upvotes: 2

Related Questions