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?
thank
+3
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? scope.all
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.
+5
source to share