Question

Is it possible to do the following:

if @user = User.friendly.find(params[:id])
    // logic here
else
    // do something if user doesn't exist
end

For some reason this throws the following error:

ActiveRecord::RecordNotFound

Was it helpful?

Solution

This is as expected.

[The] RecordNotFound [exception is raised if] No record responded to the find method. Either the row with the given ID doesn't exist or the row didn't meet the additional restrictions. Some find calls [like the find_by* methods] do not raise this exception to signal nothing was found ..

Use find_by_id (or find_by) which will return nil if the item is not found:

friendly.find_by_id params[:id]
friendly.find_by id: params[:id]

See also: Rails find getting ActiveRecord::RecordNotFound

OTHER TIPS

As suggested in Rails find getting ActiveRecord::RecordNotFound, I would use begin/end because .find is supposed to raise an exception:

begin
  @user = User.friendly.find(params[:id])
  # rest of code...
rescue ActiveRecord::RecordNotFound => e
  # other code; @user will automatically be nil since unassigned
end

But it's really a matter of personal preference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top