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.

160 CHAPTER 7 Basic access control<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 />

When you run bin/cucumber features/editing_users.feature again, the first and<br />

third scenarios pass, but the second one fails because you haven’t set the user’s admin<br />

capabilities inside the update action, as you did in the create action. To do so,<br />

remove the following line from the create action:<br />

@user.admin = params[:user][:admin] == "1"<br />

Now define a method called set_admin, which you can use in both actions. This<br />

method goes directly underneath find_user under the private keyword, as shown in<br />

the following listing.<br />

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

private<br />

def set_admin<br />

@user.admin = params[:user][:admin] == "1"<br />

end<br />

To use this method in the update action, place it directly above the call to update<br />

_attributes:<br />

set_admin<br />

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

Placing set_admin above update_attributes ensures that the user is made an admin<br />

directly before the save for update_attributes is triggered. You should also put it<br />

before the save in the create action:<br />

set_admin<br />

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

Now when you run the feature, all the scenarios pass:<br />

3 scenarios (3 passed)<br />

41 steps (41 passed)<br />

In this section, you added two more actions to your Admin::UsersController: edit<br />

and update. Admin users can now update users’ details if they please.<br />

Run rake cucumber:ok spec to ensure nothing was broken by your latest changes.<br />

You should see this output:<br />

31 scenarios (31 passed)<br />

270 steps (270 passed)<br />

# and<br />

14 examples, 0 failures, 7 pending

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

Saved successfully!

Ooh no, something went wrong!