I have two ActiveRecord
models which have a HABTM association.
I want to write a scope
to get the orphan records using Arel.
My problem is that I couldn't find a method to retrieve the arel_table
of the association. Since the relation is HABTM, there is no model to call arel_table
on.
I have the following now (which works), but I make a new arel table with the name of the join table (retrieved by using the reflect_on_association
method).
scope :orphans, lambda {
teachers = arel_table
join_table = Arel::Table.new(reflect_on_association(:groups).options[:join_table])
join_table_condition = join_table.project(join_table[:teacher_id])
where(teachers[:id].not_in(join_table_condition))
}
This produces the following SQL:
SELECT `teachers`.*
FROM `teachers`
WHERE (`teachers`.`id` NOT IN (SELECT `groups_teachers`.`teacher_id`
FROM `groups_teachers` ))
So is there any better way to retrieve the arel_table
instead of making a new one?