Alex Popov Alex Popov - 8 months ago 30
Ruby Question

How to filter the values of a model column, that don't exist in the database?

Given an array of model ids:

ids = [1, 2, 3]

How can I get an array of the ids, which do not already exist in the database? I can do:

ids.reject { |id| Model.exists?(id: id) }

but I don't want to make a separate database query for every id. What is the way to get the non-existent ids in a single database query?


You can use like given below.

ids = [1, 2, 3]
existing_ids = Model.where(id: ids).pluck(:id)
ids - existing_ids

Read more about pluck here