如何获得HABTM协会AREL表? [英] How to get the arel table of a habtm association?

查看:131
本文介绍了如何获得HABTM协会AREL表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two ActiveRecord models which have a HABTM association.

我想写一个范围使用阿雷尔得到孤立记录。

I want to write a scope to get the orphan records using Arel.

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

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.

我现在以下(其中工程),但我做的连接表的名称的新AREL表(通过使用 reflect_on_association 方法检索)。

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))
}

这生成的SQL语句:

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

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

So is there any better way to retrieve the arel_table instead of making a new one?

推荐答案

不幸的是,我相信你的解决方案是pretty的许多干净的存在,现在,是的,其实,什么样的关联本身内部确实实例化时:

Unfortunately, I believe your solution is pretty much the cleanest there is right now and is, in fact, what the association itself does internally when instantiated:

<一个href="https://github.com/rails/rails/blob/46492949b8c09f99db78b9f7a02d039e7bc6a702/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb#L7" rel="nofollow">https://github.com/rails/rails/blob/46492949b8c09f99db78b9f7a02d039e7bc6a702/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb#L7

我相信他们使用VS reflection.options的reflection.join_table [:join_table]仅在主,现在虽然

I believe the reflection.join_table they use vs reflection.options[:join_table] is only in master right now though.

这篇关于如何获得HABTM协会AREL表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆