Find or find_by_id
By Renzo Borgatti on January 27th, 2009
Tagged with: rails, finders, exceptions, programming, ruby
1 def update
2 @user = User.find(params[:id])
3 respond_to do |format|
4 if @user.update_attributes(params[:user])
5 flash[:notice] = 'User was successfully updated.'
6 format.html { redirect_to(@user) }
7 else
8 format.html { render :action => "edit" }
9 end
10 end
11 end 1 def update
2 @user = User.find_by_id(params[:id])
3 if @user
4 respond_to do |format|
5 if @user.update_attributes(params[:user])
6 flash[:notice] = 'User was successfully updated.'
7 format.html { redirect_to(@user) }
8 else
9 format.html { render :action => "edit" }
10 end
11 end
12 end
13 end- Probability that the record will be found or not. Maybe the object is not a User but something more volatile like an Object which deleted from the database when it's "consumed".
- There is a general catch mechanism by Rails when an exception raises up to the last possible moment. If you decide not to catch something you know a courtesy page can be presented and the error will be written in the log
- If you decide to catch the exception you need to know what to check and maybe you need to look at the documentation.
- Finally, there are cases where you really need to do something different if the record was not found than leave the error to rise. In this case you have the two options: find with catch or find_by_id with null checking.
