27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

190 CHAPTER 8 More authorization<br />

This error occurs because you haven’t yet defined a has_many association on the User<br />

model to the Permission model. To do so, open app/models/user.rb and add this line<br />

within the class:<br />

has_many :permissions<br />

This is another case where there’s no reason other than that it makes sense to put it<br />

directly underneath the line for the tickets association. It’s best if you group all similar<br />

methods together. With this association in place, run bin/rspec spec/controllers/<br />

tickets_controller_spec.rb, and the whole spec file passes:<br />

...<br />

3 examples, 0 failures<br />

Great! Now that the spec’s passing, unauthorized users don’t have access to the new<br />

and create actions. How about checking that those who have permissions can access<br />

these actions? Let’s check on the Creating Tickets feature. With this permission<br />

checking in place, any user with the right permissions should still be able to create<br />

tickets. Run bin/cucumber features/creating_tickets.feature to make sure. It<br />

should pass:<br />

3 scenarios (3 passed)<br />

38 steps (38 passed)<br />

Good. Users without permission to create tickets no longer can do so.<br />

Now that you’ve implemented this story, it’s time to commit. As usual, you should<br />

ensure that everything is still working by running rake cucumber:ok spec. Everything<br />

should pass:<br />

31 scenarios (31 passed)<br />

288 steps (288 passed)<br />

# and<br />

22 examples, 0 failures, 10 pending<br />

Let’s commit the changes:<br />

git add .<br />

git commit -m "Restricting creating tickets to only users<br />

➥who have permissions to do it"<br />

git push<br />

In this section, you limited the creation of tickets to only those users who’re granted<br />

permission to do so by using the Permission class and the CanCan gem.<br />

8.6 Restricting update access<br />

You just learned how to restrict access to the creation of tickets; your next step is to<br />

restrict which users can update tickets. Thankfully, you can re-use the framework<br />

that’s already in place with CanCan to make this a cinch. You can also re-use the Editing<br />

Tickets feature to test the restriction.

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

Saved successfully!

Ooh no, something went wrong!