如何获得habtm协会的arel表?

我有两个具有HABTM关联的ActiveRecord模型。

我想编写一个scope来使用Arel获取孤立记录。

我的问题是我找不到一个方法来检索关联的arel_table 。 由于关系是HABTM,因此没有模型可以调用arel_table

我现在有以下(有效),但我创建了一个新的arel表,其中包含连接表的名称(使用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)) } 

这会产生以下SQL:

 SELECT `teachers`.* FROM `teachers` WHERE (`teachers`.`id` NOT IN (SELECT `groups_teachers`.`teacher_id` FROM `groups_teachers` )) 

那么有没有更好的方法来检索arel_table而不是创建一个新的?

不幸的是,我相信你的解决方案现在几乎是最干净的,实际上,它是实例化时关联本身在内部的作用:

https://github.com/rails/rails/blob/46492949b8c09f99db78b9f7a02d039e7bc6a702/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb#L7

我相信他们使用的reflection.join_table vs reflection.options [:join_table]现在只在master中。

如果您知道关联的名称,因此知道联接表,在这种情况下它看起来像你,你应该能够调用:

 Arel::Table.new(:groups_teachers) 

在我的测试中返回一个habtm关联的Arel表。 感谢这个答案向我指出这一点。