【发布时间】:2015-06-07 11:04:00
【问题描述】:
我想搜索不属于第 1 组 (Groups) 的所有用户 (Users),并由 UserGroups 加入,即“查找所有没有将用户组记录绑定到组的用户1."
我可以使用User.all 查找所有用户或使用User.where('name like ?' , '%'+params[:search]+'%') 按名称查找他们
我什至可以找到那些没有会员资格的人:
User.includes(:user_groups).where( :user_groups => { :user_id => nil } )
但是我怎么说,“找到所有不是第 1 组成员的 Users?”
更新:这里是有效的 SQL:
select * from Users as u where not exists (select 1 from UserGroups where group_id = 1 and user_id = u.id);
或者,如果您更喜欢缓存的NOT IN
select * from Users as u where u.id not in (select user_id from UserGroups where group_id = 1);
更新:
我现在发现的唯一方法是原始 SQL,但我会喜欢真正的 ActiveRecord 方法:
User.where('name like ? and id not in (select user_id from UserGroups where group_id = ?)' , '%'+params[:search]+'%',@group.id)
【问题讨论】:
-
试试这个 --
User.includes(:user_groups).where( "user_groups.user_id != users.id AND group_id = ? ",@group.id ).where("name LIKE ?", '%'+params[:search]+'%' ).references(:user_groups) -
嗯@R_O_R,不同。而不是不在,使用连接。
-
@deith,你得到了想要的结果?
-
是的,确实如此,@R_O_R,但我正在尝试使用 ActiveRecord。看看 D-Side 的回答,太棒了。
-
好的..我没有测试我给出的代码,这就是为什么我也确认你的逻辑是否虚假.. :p 谢谢你试一试..
标签: ruby-on-rails activerecord