私は現在このコードを持っています:
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
そして、2つのクエリを生成します。
実行することが可能です
where(id: Role.select(:group_id))
そしてそれはちょうど1つのSQLクエリを生成しますが、IN
代わりにNOT IN
私が必要とします。
NOT IN
find_by_sqlを使用せずに1つのクエリで実行することは可能ですか?