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.

The projects API<br />

Then you’ll put this line under the authorize_admin! filter inside this controller’s<br />

class:<br />

before_filter :find_project, :only => [:show]<br />

Next, you need to add the find_project after the show action as a private method, as<br />

shown in the following listing.<br />

Listing 13.16 app/controllers/api/v1/projects_controller.rb<br />

private<br />

def find_project<br />

@project = Project.for(current_user).find(params[:id])<br />

rescue ActiveRecord::RecordNotFound<br />

error = { :error => "The project you were looking for " +<br />

"could not be found."}<br />

respond_with(error, :status => 404)<br />

end<br />

Here you respond with the error message and set the status to 404 to tell the user that<br />

the project doesn’t exist. When you run bin/rspec spec/api/v1/project_errors<br />

_spec.rb, your spec will pass:<br />

2 examples, 0 failures<br />

You’re now restricting the projects that a user can access to only the ones they have<br />

permission to view. If the API user doesn’t have the permission, you’ll deny all knowledge<br />

of the project and return a 404 status code. It’s quite grand how this is possible in<br />

such few lines of easy-to-understand code.<br />

You’ll run all the specs now to make sure everything’s rosy with rake spec. You<br />

should see that it’s all green:<br />

40 examples, 0 failures, 12 pending<br />

A nice round number this time. A commit you shall make:<br />

git add .<br />

git commit -m "Restricting projects API show to only users who have<br />

➥permission to view a project"<br />

git push<br />

Currently you’ve got the index, show, and create actions implemented for your controller.<br />

What’s missing? Well, you could say the new, edit, update, and destroy actions<br />

are, but you don’t need the new and edit actions, because this should be handled on<br />

the client side of the API, not the server. It is the client’s duty to present the new and<br />

edit dialogs to the user. Therefore, you only need to implement the update and<br />

destroy methods and then you’re done with this API. So close!<br />

369

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

Saved successfully!

Ooh no, something went wrong!