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

The error occurs because you’re attempting to call the [] method on something that<br />

is nil, and it’s really likely that the something is the last_ticket key, which doesn’t<br />

exist yet because the method is not defined. To define this method, open app/<br />

models/project.rb and add this method inside the class:<br />

def last_ticket<br />

tickets.last<br />

end<br />

Why are you doing it this way? Well, respond_with doesn’t let you chain methods, and<br />

so you’ll work around this by defining a method that calls the chain in your model.<br />

When you run bin/rspec spec/api/v1/projects_spec.rb, this test will pass because<br />

the last_ticket method is now defined:<br />

1 example, 0 failures<br />

Great! Now the show action is responding with data similar to 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 />

How goes the rest of your API? Let’s find out with a quick run of rake spec:<br />

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

Ok, that’s good to see, time to make a commit:<br />

git add .<br />

git commit -m "Added API action for a single project with last ticket"<br />

git push<br />

Back in the main part of the application, you’ve got permissions on users that restrict<br />

which projects they can see. Currently in the API there is no such restriction, and so<br />

you need to add one to bring it in line with how the application behaves.<br />

367

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

Saved successfully!

Ooh no, something went wrong!