chris P
chris P

Reputation: 6589

While creating a Rails JSON API, how can I use respond_with and use additional custom key/values?

Right now I have the following and it works fine...

respond_with :api, :v1, @hotel

however, I would like to be able to throw additional items on there such as...

respond_with :api, :v1, @hotel, success: :true #bad example but you get the idea

What is the syntax to do this, as what I have above does not work.

This works on my #index for an index of all hotels

 respond_with ({ success: :true, hotels: @hotels }.as_json)

but for my #create

I have to include :api :v1. Why is that, and what syntax do I need to add additional custom keys/values to my model json output?

Upvotes: 0

Views: 159

Answers (1)

pdobb
pdobb

Reputation: 18037

The index action doesn't need :api, :v1 because it's not responding with a URL to the show action of a created resource.

The second part of the question has a pretty complex answer... Basically, to keep things simple in the controller you'll want to override the as_json method in the model so that the model takes care of outputting the values on its own. But directly adding an as_json override in a model is discouraged so that your api can progress (v2, v3, ...) independently as the application ages. The solution I use is to create Presenters based on the api version so the model presentation happens in a loosely-coupled way. Since this is a fairly complex topic I'm just going to provide a few links to get you started down that path:

http://www.railstips.org/blog/archives/2011/12/01/creating-an-api/ http://josephhsu.com/post/32746478033/rails-responders-api-versioning

Upvotes: 1

Related Questions