简体   繁体   English

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

[英]Rails exclusion query with active record — Rails 3.1

How would I use active record in this case: 在这种情况下,我将如何使用活动记录:

I have two tables: Users, Admins 我有两个表:Users,Admins

Admins can be users also and thus have a user_id in their table. 管理员也可以是用户,因此表中有一个user_id。

I'd like to Select all users that DO NOT have a user_id set in the admins table 我想选择所有未在admins表中设置user_id的用户

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 : 您可以使用:conditions包含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 ): 或者,您可以将其编码到用户的scope (在Rails 3.x之前也称为named_scope ):

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 : 或者为了不依赖于传递@admins变量,可以使用joins

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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