Rails find with ID NOT IN clause, how to maintain display value null?

I want to show the user all the groups they are not currently members of. The following works fine when the user is in at least one group:

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


This fails if the user is in 0 groups and @groups.map(&:id)

is null. How can I update the above to maintain a use case where @ groups.map (&: id) is null / nill in ruby ​​on rails?



source to share

4 answers

Rails 3 includes AREL, which allows you to create piecewise functions. This is very convenient under these circumstances.

scope = Group
group_ids = @groups.map(&:id)
scope = scope.where(['id not in (?)', group_ids]) unless group_ids.empty?


What it will do is only a condition NOT IN

if to exclude group IDs. When the exclusion groups are empty, they will not include it in the request.



Simplest workaround:

Group.where(['id NOT IN (?)', @groups.map(&:id).presence || [0]])


Using Arel works as expected without any hacks:





This is probably for scope:

class Group < ActiveRecord::Base
  scope :search_excluding_ids, lambda { |g| 
      g.present? ? where(['id not in (?)', group_ids]) : {}





Since there is no answer to this question, will post what helped on Rails 2.3 and Ruby 1.9.3:

Group.find(:all, :conditions => ['id not in (?), @groups.map(&:id).join(",")])



All Articles