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.

Sign up to request clarification or add additional context in comments.

5 Comments

This answers my question, but applies to all Cars. Is there a way to do this only for a particular controller only?
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.
hmm, started working suddenly, maybe a caching issue.
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)}
That sounds perfect @MartinM, seems odd that I can pass an array of JSON strings instead of Car objects.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.