【发布时间】:2012-11-08 08:07:45
【问题描述】:
我目前有这个代码:
class Group < ActiveRecord::Base
has_many :roles
#can't find better name for this method
def self.without_role_ids
find_by_sql('select id from groups where id not in
(select distinct group_id from roles)').map { |g| g.id }
end
end
class Role < ActiveRecord::Base
belongs_to :group
end
without_role_ids 方法输出没有任何角色的组的 ID。
我想做的是重写这个方法:
def self.without_role_ids
where("id NOT IN (?)", Role.pluck(:group_id))
end
它会产生两个查询。
可以运行
where(id: Role.select(:group_id))
它将只产生一个 SQL 查询,但使用 IN 而不是我需要的 NOT IN。
是否可以在不使用 find_by_sql 的情况下通过一个查询来执行 NOT IN?
【问题讨论】:
标签: ruby-on-rails activerecord ruby-on-rails-3.2