Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to append data to json in ruby/rails?

Tags:

Say i have this short code:

item = Item.find(params[:id]) render :json => item.to_json 

but i needed to insert/push extra information to the returned json object, how do i do that?

Lets say i need to insert this extra info:

message : "it works" 

Thanks.

like image 780
David Avatar asked Jun 30 '10 06:06

David


2 Answers

item = Item.find(params[:id]) item["message"] = "it works" render :json => item.to_json 
like image 59
Dogbert Avatar answered Sep 21 '22 03:09

Dogbert


The to_json method takes an option object as parameter . So what you can do is make a method in your item class called as message and have it return the text that you want as its value .

class Item  < ActiveRecord::Base  def message   "it works"  end end  render :json => item.to_json(:methods => :message) 
like image 37
NM. Avatar answered Sep 24 '22 03:09

NM.