且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有活动记录的 Rails 排除查询 -- Rails 3.1

更新时间:2023-09-24 11:13:04

你可以使用 :conditions 来包含一个 NOT IN:

You can use :conditions to include a NOT IN:

User.find(:all, :conditions => ['user_id not in (?)', @admins.map( &:id )])

OR 您可以将其编码到用户的 scope(也称为 Rails 3.x 之前的 named_scope )中:


OR you can code it into a User's scope ( a.k.a. named_scope prior to Rails 3.x ):

class User < ActiveRecord::Base
  scope :not_admin, lambda { |admins| { :conditions => ['user_id not in (?)', admins.select( &:id ).join( ',' )] }
end

并将其用作:

User.not_admin( @admins )

OR 为了不依赖于传递的 @admins 变量,您可以使用 joins:


OR in order not to depend on @admins variable being passed you can use joins:

class User < ActiveRecord::Base
  scope :not_admin, joins( :admin ).where( :admins => { :user_id => nil } )
end