3

I am trying to render multiple objects as JSON. This is my render call:

render :json => {:widget => @widget.to_json(:include => :foo), 
                 :updated => Time.now.to_i}

I have to use to_json because of the include, and the addition updated so I know when the last call was made. The problem is that the to_json is rendered as a String instead of the object structure of the widget.

How do I get the full object structure of the widget and the updated information?

1 Answer 1

1

Move the :include => :foo into your Widget model.

class Widget < ActiveRecord::Base
  def as_json(options = {})
    super options.merge(:include => :foo)
  end
end
Sign up to request clarification or add additional context in comments.

4 Comments

interesting, how to I ensure the options get passed as well? something easy like merge...
It's not working... render :json => {:widget => @widget, :updated => time} does not include the :foo object
so... small change, @widget isn't a single widget, it is an array of widgets. I have the include in the call to the db (Widget.includes(:foo).limit(10)), and that doesn't populate the object either.
I had a typo and wrote to_json when I meant as_json. It should work for an array of those objects as well. At least, it has when I've done it. If it's not working for you, please post maybe the real code instead of the mock-up.

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.