Generating JSON with Rails? -


i need generate json string looks 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 way generate json strings?

the right way using jbuilder part of rails.

so documentation:

# app/views/message/show.json.jbuilder  json.content format_content(@message.content) json.(@message, :created_at, :updated_at)  json.author   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 |attachment|   json.filename attachment.filename   json.url url_for(attachment) end 

this build following structure:

{   "content": "<p>this <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' <david@heinemeierhansson.com>",     "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 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 case code should like:

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

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -