假设我有以下这段简短的代码:
item = Item.find(params[:id])
render :json => item.to_json
但是我需要向返回的JSON对象中插入/推送额外信息,我该怎么做?
假设我需要插入这个额外信息:
message : "it works"
谢谢。
假设我有以下这段简短的代码:
item = Item.find(params[:id])
render :json => item.to_json
但是我需要向返回的JSON对象中插入/推送额外信息,我该怎么做?
假设我需要插入这个额外信息:
message : "it works"
谢谢。
item = Item.find(params[:id])
item["message"] = "it works"
render :json => item.to_json
to_json
方法接受一个 option object as parameter 作为参数。因此,您可以在您的项目类中创建一个名为 message 的方法,并将其返回要作为其值的文本。
class Item < ActiveRecord::Base
def message
"it works"
end
end
render :json => item.to_json(:methods => :message)
我发现现在Rails 3.2.13中,原先被接受的解答现在已经出现了弃用警告。
弃用警告:您正在尝试创建一个属性。 在模型上编写任意属性已过时。 请使用
attr_writer
等方法。
假设您不想将建议的attr_writer
放入您的模型中,您可以使用as_json
方法(返回哈希)来调整您的JSON响应对象。
item = Item.find(params[:id])
render :json => item.as_json.merge(:message => 'it works')
as_json
返回一个数组,而数组没有名为 merge
的方法。
有一种方法可以将项目对象转换为哈希,然后简单地添加 :message
。例如render json: Hash[[*item.map.with_index]].invert[:message] = 'it works'
转换为哈希
链接 - jmeinlschmidtrender json: {items: item, message: 'it works'}
- jmeinlschmidt如果您使用脚手架,例如:
rails generate scaffold MyItem
app/view/my_item/_my_item.json.jbuilder
app/view/my_item/index.json.jbuilder
所以,您可以为项目添加自定义数据到JSON输出中,只需添加以下内容:
json.extract! my_item, :id, :some_filed, :created_at, :updated_at
json.url my_item_url(my_item, format: :json)
json.my_data my_function(my_item)
正如您所看到的,可以修改一个项目的JSON输出,也可以修改索引的JSON输出。
我总是使用:
@item = Item.find(params[:id])
render json: { item: @item.map { |p| { id: p.id, name: p.name } }, message: "it works" }
你试过这个吗?
item = Item.find(params[:id])
item <<{ :status => "Success" }
render :json => item.to_json
items = Item.all
items["message"] = "it works"
render json: items.to_json
代码会报错'no implicit conversion of String into Integer'。 - sabramsitem = item.as_json
需要添加到第二行?还没有测试过。 - NamNamNam