Displaying Error Messages with the Action Pack Library
In this ninth part of a multi-part series on the Action Pack library for Rails, you'll learn how to displya error messages in templates, and more. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
Displaying Error Messages with the Action Pack Library - Adding the Edit Form (Page 2 of 2 )
The next step is to add the edit and update actions to the controller. Weíll also need an edit template. Create a new action called edit, as shown in Listing 6-6 (it looks a lot like the new action).
Listing 6-6. Edit Action Added to app/controllers/users_controller.rb
def edit @user = User.find(params[:id]) end
Next, create the edit template in app/views/users/edit.rhtml as shown in Listing 6-7.
Listing 6-7. The app/views/users/edit.rhtml Template
<% form_tag :action => 'update' do %> <p></p>
<p><%= submit_tag 'Save Changes' %></p> <% end %>
As you can see from the form_tag method, this form will submit to the update action on the events controller. We need to add the update method to our controller, so letís do that now, as shown in Listing 6-8.
Listing 6-8. Update Action Added to app/controllers/users_controller.rb
@user = User.find(params[:id])
flash[:notice] = 'Information updated' redirect_to :action => 'show', :id => @user.id else render :action => 'edit' end end
The update action looks almost identical to the create action. The main difference is that instead of instantiating a new User object, weíre fetching an existing one. We use Active Recordís update_attributes method to update all the User attributes with those from the params hash and save it in one shot. If the update fails, update_attributes will return false , and our if statement will take the else path.
You canít help but notice that the new and edit templates look essentially the same. Given Railsí emphasis on DRY, as you would expect, thereís a way to clean this up, and thatís what weíll look at next.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.