In my Item controller, I want to add a transient (i.e. mutable) attribute to my model object before rendering it as JSON.
def show
@item = Item.find(params[:id])
@item.comment = "some comment"
render :json => @item
end
The My Item class is as follows:
class Item < ActiveRecord::Base
attr_accessor :comment
@comment
end
My problem is that the comment instance variable is not displayed in JSON. At the output of JSON, everything appears constantly. Do I need to override the to_json method to make this work? Or is there an easier way to ensure that a comment is displayed in JSON output?
Thank you for your help.
-------------- Update
This is a decision that emerged from Chubas’s proposal. Overriding the to_json method by element:
def to_json(options = {})
options[:methods] = :comment;
super(options)
end
I would like to know if this is consistent with your thoughts, Chubas.