Tag: Rails/JSON
book = Book.new book.title = "abc" json = book.to_json # puts jsonでもよいがわかりやすくフォーマットしたい場合以下を使う。 puts JSON.pretty_generate(JSON.parse(json))
{ "id": null, "title": "abc", "author": null, "summary": null, "created_at": null, "updated_at": null, }
ActiveRecord::Base.include_root_in_json = false book = Book.new book.title = "abc" json = book.to_json(root: true) #puts json puts JSON.pretty_generate(JSON.parse(json))
{ "book": { "id": null, "title": "abc", "author": null, "summary": null, "created_at": null, "updated_at": null, } }
def as_json(options = nil) root = if options && options.key?(:root) options[:root] else include_root_in_json end result = super(options) h = result if root h = result[model_name.element] end h["custom_title"] = "custom #{title}" result end
{ "book": { "id": null, "title": "abc", "author": null, "summary": null, "created_at": null, "updated_at": null, "custom_title": "custom abc" } }