27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

7.7.2 The edit and update actions<br />

Editing users<br />

Add the edit action directly underneath the create action in your controller. It<br />

should be another blank method like the show action:<br />

def edit<br />

end<br />

With this action defined and the @user variable used in its view already set by the<br />

before_filter, you now create the template for this action at app/views/admin/<br />

users/edit.html.erb. This template renders the same form as the new template:<br />

<br />

When you run bin/cucumber features/editing_users.feature, you’re told the<br />

update action doesn’t exist:<br />

The action 'update' could not be found for Admin::UsersController<br />

Indeed, it doesn’t, so let’s create it! Add the update action to your Admin::Users-<br />

Controller, as shown in the following listing. You needn’t set up the @user variable<br />

here because the find_user before_filter does it for you.<br />

Listing 7.28 app/controllers/admin/users_controller.rb<br />

def update<br />

if @user.update_attributes(params[:user])<br />

flash[:notice] = "User has been updated."<br />

redirect_to admin_users_path<br />

else<br />

flash[:alert] = "User has not been updated."<br />

render :action => "edit"<br />

end<br />

end<br />

With this action in place, you need to delete the password parameters from<br />

params[:user] if they are blank. Otherwise, the application will attempt to update a<br />

user with a blank password, and Devise won’t allow that. Above update_attributes,<br />

insert this code:<br />

if params[:user][:password].blank?<br />

params[:user].delete(:password)<br />

end<br />

Now the entire action looks like the following listing.<br />

Listing 7.29 app/controllers/admin/users_controller.rb<br />

def update<br />

if params[:user][:password].blank?<br />

params[:user].delete(:password)<br />

params[:user].delete(:password_confirmation)<br />

end<br />

if @user.update_attributes(params[:user])<br />

159

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!