ruby on rails - ActiveRecord 'where' clause not working if filter array is empty -


i'd fetch active relations id's not in array. this:

    @widgets = widget.where("id not in (?)", [1, 2, 3]) 

this works fine. returns full widget table except records excluded filter array. however, if filter array empty, doesn't work.

    @widgets = widget.where("id not in (?)", []) 

returns "[]", when equivalent of widget.all

i have worked around testing first if filter array empty, , modifying query. workaround seems kludge. there way express 'where' clause returns entire table if filter array empty?

you can add scope widget model:

scope :excluding_ids, ->(ids) { where('id not in (?)', ids) if ids.any? } 

then it's matter of doing wherever need it:

@widgets = widgets.excluding_ids([1,2,3]) 

Comments