views:

32

answers:

3

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

A: 

I think this will work, I haven't tested it.

if @permission
  # Handle when the permission exists
else
  # Handle when the permission doesn't exist
end
errorhandler
`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. (-1 for incorrect information and not testing)
Platinum Azure
+4  A: 
@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.

Matt Briggs
+1  A: 

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])
Platinum Azure
Ah, I forgot about `find_by_[column]`. Use that instead (see Matt Briggs' answer). It might be a little slower due to `method_missing` but it's more intuitive.
Platinum Azure