如何在ruby / rails中将数据附加到json?

说我有这个简短的代码:

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方法将选项对象作为参数 。 所以你可以做的是在你的item类中创建一个名为message的方法,让它返回你想要的文本作为它的值。

 class Item < ActiveRecord::Base def message "it works" end end render :json => item.to_json(:methods => :message) 

我发现接受的答案现在抛出了Rails 3.2.13中的弃用警告。

弃权警告:您正在尝试创建属性message'. Writing arbitrary attributes on a model is deprecated. Please just use message'. Writing arbitrary attributes on a model is deprecated. Please just use message'. Writing arbitrary attributes on a model is deprecated. Please just use attr_writer`等。

假设您不想将建议的attr_writer放在模型中,可以使用as_json方法(返回Hash)来调整JSON响应对象。

 item = Item.find(params[:id]) render :json => item.as_json.merge(:message => 'it works') 

如何将数据附加到ruby / rails中的json 5

如果您使用脚手架,例如:

 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]) item <<{ :status => "Success" } render :json => item.to_json