I have two models ActiveRecordthat have a HABTM association.
I want to write scopeto get orphaned entries using Arel.
My problem is that I could not find a method to extract arel_tablefrom the association. Since the relationship is HABTM, there is no model to call arel_tableon.
Now I have the following (which works), but I create a new isl table with the name of the join table (retrieved using the method reflect_on_association).
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))
}
As a result, the following SQL is created:
SELECT `teachers`.*
FROM `teachers`
WHERE (`teachers`.`id` NOT IN (SELECT `groups_teachers`.`teacher_id`
FROM `groups_teachers` ))
So, is there a better way to get arel_tableinstead of creating a new one?
source
share