jmasterx
jmasterx

Reputation: 54103

Generating JSON with Rails?

I just need to generate a JSON string that looks something like:

def self.feedback_request(history_event)
    @event = history_event.event
    @case_tracking_id = history_event.case_tracking_id
    @request_type = "feedback"
   return "{
        "event":@event
        "case_tracking_id":@case_tracking_id
        "request_type":@request_type
        "event_data":historic_event.to_json
     }"
end

Does rails have some way to generate JSON strings?

Upvotes: 1

Views: 55

Answers (1)

Paulo Fidalgo
Paulo Fidalgo

Reputation: 22296

The right way to do it is using the jbuilder which is part of Rails.

so from the documentation:

# app/views/message/show.json.jbuilder

json.content format_content(@message.content)
json.(@message, :created_at, :updated_at)

json.author do
  json.name @message.creator.name.familiar
  json.email_address @message.creator.email_address_with_name
  json.url url_for(@message.creator, format: :json)
end

if current_user.admin?
  json.visitors calculate_visitors(@message)
end

json.comments @message.comments, :content, :created_at

json.attachments @message.attachments do |attachment|
  json.filename attachment.filename
  json.url url_for(attachment)
end

This will build the following structure:

{
  "content": "<p>This is <i>serious</i> monkey business</p>",
  "created_at": "2011-10-29T20:45:28-05:00",
  "updated_at": "2011-10-29T20:45:28-05:00",

  "author": {
    "name": "David H.",
    "email_address": "'David Heinemeier Hansson' <[email protected]>",
    "url": "http://example.com/users/1-david.json"
  },

  "visitors": 15,

  "comments": [
    { "content": "Hello everyone!", "created_at": "2011-10-29T20:45:28-05:00" },
    { "content": "To you my good sir!", "created_at": "2011-10-29T20:47:28-05:00" }
  ],

  "attachments": [
    { "filename": "forecast.xls", "url": "http://example.com/downloads/forecast.xls" },
    { "filename": "presentation.pdf", "url": "http://example.com/downloads/presentation.pdf" }
  ]
}

So in you case your code should be something like:

json.(@event, @case_tracking_id, @request_type, historic_event)

Upvotes: 1

Related Questions