views:

37

answers:

3

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.

+1  A: 
item = Item.find(params[:id])
item["message"] = "it works"
render :json => item.to_json
Adam
Wouldn't this line throw and error : item["message"] = "it works" .As far as I know you can not add properties dynamically like this in ruby ( you could do something like this in js though ) .
NM
This would work, but only if item was/is a hash. You can dynamically add properties to hashes.
mpd
Does ActiveRecord return a hash ?
NM
Adam's code works perfectly.
David
+1  A: 

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)
NM
A: 

Have you tried this ?

item = Item.find(params[:id]) 
item <<{ :status => "Success" }

render :json => item.to_json
Suprie