使用Rails生成JSON?

时间:2015-06-18 17:55:36

标签: ruby-on-rails json

我只需要生成一个类似于:

的JSON字符串
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

rails是否有某种方法来生成JSON字符串?

1 个答案:

答案 0 :(得分:1)

正确的方法是使用jbuilder,这是Rails的一部分。

所以从文档:

# 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

这将构建以下结构:

{
  "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' <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 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" }
  ]
}

所以在你的情况下你的代码应该是这样的:

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