带有活动记录的 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
管理员也可以是用户,因此他们的表中有一个 user_id.
Admins can be users also and thus have a user_id in their 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.
再一次,我知道这样做的语义是糟糕的数据库设计——但这只是一个假案例.
Again, I know the semantics of doing it like this is terrible db design -- but it's just an dummy case.
推荐答案
你可以使用 :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
这篇关于带有活动记录的 Rails 排除查询 -- Rails 3.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!