Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify JSON returned from Rails controller

The standard mechanism I return JSON in a Rails controller is with:

respond_to do |format|
  format.html
  format.json { render json: @cars }
end

Is there a way to modify the @cars JSON? In particular I simply want to add 4 extra fields in there.

UPDATE: Sorry, I should've explained a little more. @cars contains a list of Car objects. I want to add 4 fields to each Car object in the JSON. This is unique to a particular controller, so I don't want to make an as_json method as that would affect other JSONs of this class.

like image 460
at. Avatar asked May 02 '26 08:05

at.


2 Answers

You can also add custom or nested fields with something like:

class MyModel < ActiveRecord::Base

  def as_json(options)
    super(options).merge({
      "custom" => "myvalue",
      :name => self.name.titleize,
      "result" => self.my_method(self.value1)
    })
  end
end
like image 92
nakwa Avatar answered May 03 '26 22:05

nakwa


If you have to do it once, you should use to_json ( http://apidock.com/rails/ActiveRecord/Serialization/to_json ) in this way, directly in your controller:

@object.to_json(:except => ['created_at', 'updated_at'], :methods => ['method1', 'method2'])

In :methods you can specify additional methods you want include.

activemodel_serializer should be used only if you do it very often (for example on a JSON API), if you do it only once in your project, you shouldn't do it.

You can also use the default Rails 4 builder if you are actually using Rails 4.
Notice that the most famous gem for building JSON is RABL, but I do prefer activemodel_serializer. There is also a very nice railscasts available for free about it.

like image 39
Francesco Belladonna Avatar answered May 03 '26 23:05

Francesco Belladonna