简体   繁体   中英

Rails exclusion query with active record — Rails 3.1

How would I use active record in this case:

I have two tables: Users, Admins

Admins can be users also and thus have a user_id in their table.

I'd like to Select all users that DO NOT have a user_id set in the admins table

NOTE: This is just an example case. If this was a real case then of course I wouldn't have two different tables for users and admins.

Edit: Again, I know the semantics of doing it like this is terrible db design -- but it's just an dummy case.

You can use :conditions to include a NOT IN :

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

OR you can code it into a User's scope ( aka 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

And use it as:

User.not_admin( @admins )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM