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 />

class Admin::PermissionsController < Admin::BaseController<br />

before_filter :find_user<br />

end<br />

Listing 8.15 app/controllers/admin/permissions_controller.rb<br />

def index<br />

@ability = Ability.new(@user)<br />

@projects = Project.all<br />

end<br />

private<br />

def find_user<br />

@user = User.find(params[:user_id])<br />

end<br />

The new Ability instance created here lets you check the user’s ability to perform<br />

specific actions on any project by simply calling this code:<br />

@ability.can?(:"view", @project)<br />

This syntax may look similar to the syntax used in TicketsController—it is. In that<br />

controller, you used the cannot? method, which is the opposite of the can? method.<br />

These methods are added to the controller by CanCan and are just shorter helper<br />

methods to do almost exactly what you did in this controller. The only difference is<br />

that you’re not acting on the current_user here, so you must define an Ability<br />

object yourself and use that instead.<br />

THE PERMISSIONS SCREEN<br />

Now that you have the index action up, you need to make its view look like what is<br />

shown in figure 8.5. Create a new file at app/views/admin/permissions/index.html.erb,<br />

and fill it with the content from the following listing.<br />

Figure 8.5 The permissions screen<br />

201

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

Saved successfully!

Ooh no, something went wrong!