Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails scope that does nothing for NOT IN values

I have a Rails 3 scope that excludes an array of ids.

What is the best way to write the scope so that it does nothing when the array is empty and is still chainable? I currently have this, which works, but seems a little hokey:

scope :excluding_ids, 
         lambda {|ids| ids.empty? ? relation : where('id not in (?)', ids) }

If I do not have the "ids.empty? ? relation :" bit, when ids is empty the SQL generated is

... ID not in (NULL) ...

which will always return nothing. So something like:

Model.excluding_ids([]).where('id > 0')

returns no results.

like image 946
tee Avatar asked Apr 01 '11 21:04

tee


1 Answers

In Rails 4 you can use:

scope :excluding_ids, ->(ids) { where.not(id: ids) }
like image 67
GuiGS Avatar answered Sep 19 '22 17:09

GuiGS