LuckyLuke
LuckyLuke

Reputation: 49047

Exposing data as XML and JSON in Rails

I am trying to understand how I can expose my data in XML and JSON. I have made HTML views for the data now, but I don't understand much of the respond_to block and how you can respond with JSON and XML....and at the same time have control on the structure. Can somebody please help me with where I should start reading and learn how to do this? I haven't had much luck searching for it myself.

Upvotes: 1

Views: 398

Answers (2)

niiru
niiru

Reputation: 5102

I use the rabl gem to format the JSON I expose.

Your respond_to block for your users_controller#show action could look like:

respond_to do |format|
  format.html
  format.json
end

Then you can create a rabl template in /app/views/users/show.json.rabl:

object @user
attributes :id, :username, :first_name, :last_name

You can find more about rabl here

Upvotes: 2

davidrac
davidrac

Reputation: 10738

You can start by reading this guide. It gives a pretty good idea of how rendering works in rails.

This article is also very helpful.

Upvotes: 2

Related Questions