Alex Popov Alex Popov - 2 years ago 75
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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download