Ruby on Rails: problem of adding a transition attribute to an object for JSON Serializaton

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.

+3
4

, , json- ( ), as_json , methods :comment.

+1

, json . , , , .

- :

render :json => {
  :item => {
    :name => 'Some Item',
    ...
    :comment => 'Some Comment
  }
}
+2

, : include

@item.to_json(:include => :comments)

:

@item.to_json(:methods => :comments)
+1

, to_json. to_json?

@object[:new_attr] = value
0
source

Source: https://habr.com/ru/post/1761545/


All Articles