3

私は現在このコードを持っています:

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 INfind_by_sqlを使用せずに1つのクエリで実行することは可能ですか?

4

1 に答える 1

3

私は解決策を見つけました、Squeelでそのようなクエリを実行するのは簡単です:

https://github.com/ernie/squeel

現在、メソッドコードは次のとおりです。

where{id.not_in Role.select(:group_id)}

そしてそれはこのクエリを生成します:

SELECT "groups".* FROM "groups" WHERE "groups"."id" NOT IN
  (SELECT "roles"."group_id" FROM "roles" )

Squeelに関するRailscastがあります:http://railscasts.com/episodes/354-squeel

于 2012-11-08T08:07:45.547 に答える