D
D
Demigodd2019-01-30 11:32:23
Ruby on Rails
Demigodd, 2019-01-30 11:32:23

How to return all Models if id is nil in Rails?

How to return all Models if id is nil in Rails ?

arr_id = [1, 2, 3]

Model.where(id: arr_id)

For example, if here arr_id is nil or an empty array, then how to remove this Where check ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
oh_shi, 2019-01-30
@Demigodd

def self.filter_id(arr_id)
  if arr_id.present?
    where(id: arr_id)
  else
    all
  end
end

or
scope :filter_id, -> arr_id { where(id: arr_id) if arr_id.present? }

S
Sergey Blokhin, 2019-01-30
@TITnet

if arr_id.nil? || arr_id.empty?
  Model.all
else
  Model.where id: arr_id
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question