Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - How to Not to Error if no record is found

In my permissions controller, I use Active record to look for a permission:

@permission = Permission.find(params[:user_id])

If this returns a result I then look up the permission.name And pass this to my controller.

Problem is sometimes this does returna result, othertimes it does not. When it does not, it errors. How can I prevent that from occuring?

Use Case: 1. If the user does have a permission record, show it and let the user change it 2. If not, show they don't have a permission record and allow the user to set a permission.

Thanks

like image 980
WozPoz Avatar asked Oct 11 '10 21:10

WozPoz


4 Answers

@permission = Permission.find_by_id params[:user_id]

The idea is that if you are using the "first param is the id" version of find, you know exactly what you are looking for, and if it isn't there, thats a problem. If you use one of the more generic finder syntaxes (like find_by_field_name), the assumption is that if it isn't there, that is an acceptable situation so just return nil.

like image 94
Matt Briggs Avatar answered Nov 15 '22 14:11

Matt Briggs


I know this is old, but I just found this and I want to suggest a different way of handling this situation. ActiveRecord::RecordNotFound is nothing to be afraid of. A user may pass in a valid record id, but that record may not belong to them (i.e. if you do something like current_user.widgets.find(params[:id])). I prefer to handle it like this:

def show
  begin
    @permission = Permission.find(params[:user_id])
  rescue ActiveRecord::RecordNotFound
    # however you want to respond to it
  end
end
like image 27
clem Avatar answered Nov 15 '22 13:11

clem


ActiveRecord#find with an int parameter is a targeted find. Rails raises RecordNotFound if the record isn't found.

This is different from using find with parameters like :first or :all, which is more of a search; Rails returns nil for no records in those cases. If you want to avoid the raising of an exception, use one of those options or the corresponding method names.

Example:

@permission = Permission.find(:first, :id => params[:id])
like image 44
Platinum Azure Avatar answered Nov 15 '22 15:11

Platinum Azure


The other way:

@permission = Permission.find_all_by_id params[:user_id]

I think that it useful if user_id is a array

like image 2
taivn07 Avatar answered Nov 15 '22 13:11

taivn07