Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord find array of ids, but some are not found

I am trying to find a model by an array of ids like so:

Model.find [1,2,3]

but let's say only two of these models exist (the model with id of 2 was deleted):

#<Model id: 1>
#<Model id: 3>

I get an error like this:

#<ActiveRecord::RecordNotFound: Couldn't find all Models with 'id': (1, 2, 3) (found 2 results, but was looking for 3).>

Is it possible to catch this error and determine which of the models were not present?

say i'm in my controller:

def index
  @models = Model.find params.require(:model_ids)
rescue ActiveRecord::RecordNotFound => e
  e.full_message
  ???
end

I'd like to, in the ??? line, run some code on the exception e that will return 2, letting me know what of the models was not found, so I can re-run the query without it while noting which ones weren't found.

like image 496
goddamnyouryan Avatar asked Dec 18 '25 19:12

goddamnyouryan


1 Answers

Wrong method. .find should be used to find specific records when you want the code to raise ActiveRecord::RecordNotFound. This is done to ensure that the record exists and avoid nil errors. Typically this is used to trigger a 404 response without repeating the same boilerplate:

def show
  @record = Record.find_by(id: params[:id])
  unless @record
    render file: 'public/404.html', status: :not_found
  end
end

Use .find_by(id: id) if you don't want the code to raise.

To fetch multiple records use where:

models = Model.where(id: [1,2,3])

If you want to determine which of those ids don't exist use an array diff:

bad_ids = [1,2,3] - models.ids
like image 82
max Avatar answered Dec 20 '25 10:12

max



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!