1

At the end of a standard Rails controller there is:

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

Works as expected. Except the JSON doesn't have the associations of @cars:

class Car < ActiveRecord::Base attr_accessible :model, :color belongs_to :manufacturer end 

The JSON doesn't have the fields of the manufacturer. How do I get the JSON to have those? Is there something I add to the belongs_to call? Is there a way I can add it to the object created from format.json?

    2 Answers 2

    2

    By default, as_json, the method, that converts an object to JSON, includes all attributes. But manufacturer is is a method.

    You can instruct as_json to include the manufacturer with the option :methods, see api doc.

    So your Car model could loo like

    class Car < ActiveRecord::Base belongs_to :manufacturer def as_json(options={}) super(options.merge methods: :manufacturer_json) end def manufacturer_json manufacturer.as_json end end 

    to include the manufacturer.

    5
    • This answers my question, but applies to all Cars. Is there a way to do this only for a particular controller only?
      – at.
      CommentedFeb 12, 2014 at 1:26
    • Not working for me, I don't see any of my extra fields. I'm returning back {name: 'abcdef'}.as_json from manufacturer_json. But the JSON is exactly as before, no name field.
      – at.
      CommentedFeb 12, 2014 at 1:32
    • hmm, started working suddenly, maybe a caching issue.
      – at.
      CommentedFeb 12, 2014 at 1:34
    • you can drop the as_json definition in Car and set the option in the controller: render json: @cars.map{|c| c.as_json(methods:manufacturer_json)}
      – Martin M
      CommentedFeb 12, 2014 at 8:18
    • That sounds perfect @MartinM, seems odd that I can pass an array of JSON strings instead of Car objects.
      – at.
      CommentedFeb 12, 2014 at 8:19
    1

    My favorite way to do this is with the Active Model Serializer gem. With the use of custom serializers, you can achieve almost any JSON structure you'd like, with the exception of using Active Model Serializer for Has Many Through associations, which is currently being overhauled.

    You might want to take a look at some tutorials like http://robots.thoughtbot.com/fast-json-apis-in-rails-with-key-based-caches-and

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.