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

With this new authorization added you will make a commit, but before that you’ll run<br />

a customary check to make sure everything is still alright by running rake spec,<br />

because all you’ve edited in this section is the API. You should see this output:<br />

47 examples, 0 failures, 19 pending<br />

Great, so let’s go ahead and commit this then:<br />

git add .<br />

git commit -m "Only admins are able to create projects through API"<br />

git push<br />

In the response for your create action, the headers point to a location (you customized)<br />

of a project, something such as http://example.com/api/v1/projects/1. Currently,<br />

this URL doesn’t go anywhere because it needs the show action to exist. You<br />

should probably get on to that.<br />

13.1.8 A single project<br />

You’ve got a link (http://example.com/api/v1/projects/1) provided by your create<br />

action that doesn’t go anywhere if people try to access it. Soon this URL will show a<br />

particular project’s attributes through the show action in your Api::V1::Projects-<br />

Controller. Within those attributes, you’ll also show a last_ticket element, which<br />

will contain the attributes for the most recently updated ticket. To do this, you use<br />

another option of respond_with, the :methods option. Using this option will change<br />

the output of each project resource in your JSON API to something like this:<br />

{<br />

}<br />

"project": {<br />

"created_at": "[timestamp]",<br />

"id": 1,<br />

"name": "Ticketee",<br />

"updated_at": "[timestamp]",<br />

"last_ticket": {<br />

"ticket": {<br />

"asset_updated_at": null,<br />

"created_at": "[timestamp]",<br />

"description": "A ticket, nothing more.",<br />

"id": 1,<br />

"project_id": 1,<br />

"state_id": null,<br />

"title": "A ticket, nothing more.",<br />

"updated_at": "[timestamp]",<br />

"user_id": 2<br />

}<br />

}<br />

}<br />

Using the last_ticket method, people using the API will be able to discover when<br />

the last activity was on the project. You could add other fields such as the comments<br />

too if you wished, but this example is kept simple for quality and training purposes.<br />

365

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

Saved successfully!

Ooh no, something went wrong!