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.

Assigning permissions<br />

method, you must define another named route in your config/routes.rb file using the<br />

put method:<br />

put '/admin/users/:user_id/permissions',<br />

:to => 'admin/permissions#update',<br />

:as => :update_user_permissions<br />

With this method, you define a new route for your application that will only respond<br />

to PUT requests to this route. The :user_id inside the route is a variable and is passed<br />

to the action as params[:user_id]. The controller and action are defined using the<br />

:to symbol, and finally the method itself is given a name with the :as option.<br />

Now when you run the feature again, this route method is defined, but the<br />

permissions method isn’t:<br />

And I follow "Permissions"<br />

undefined local variable or method 'permissions' [...]<br />

➥(ActionView::Template::Error)<br />

Great! It seems like your page just requires this permissions helper method.<br />

DEFINING A HELPER METHOD<br />

Back in chapter 6, you defined a helper method called admins_only in Application-<br />

Helper, which allowed you to show links only for admin users. This time, you define<br />

the permissions method, which contains a list of permissions to display check boxes<br />

on this page. Because this method is specific to views from the Admin ::Permissions-<br />

Controller controller, place it in app/helpers/admin/permissions _helper.rb and<br />

define it as shown in the following listing.<br />

Listing 8.17 app/helpers/admin/permissions_helper.rb<br />

module Admin::PermissionsHelper<br />

def permissions<br />

{<br />

"view" => "View"<br />

}<br />

end<br />

end<br />

This permissions method returns a hash containing only one key-value pair at the<br />

moment because you’re testing only one particular check box. You use this method to<br />

display all the permissions you want to be configurable by admins, and you revisit this<br />

method later to define more pairs. You use this method in your view twice; the first<br />

time, you iterate over it like this:<br />

<br />

<br />

<br />

When you iterate over a Hash object with the each method, the key for the hash<br />

becomes the first block variable and the value becomes the second block variable;<br />

these variables change for each key-value pair of the Hash object. In this case, it renders<br />

headers for the table in this view. You use this helper later in the view too:<br />

203

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

Saved successfully!

Ooh no, something went wrong!