Rendering json with default options.

10 views
Skip to first unread message

Nicolas Buduroi

unread,
Aug 1, 2011, 2:50:55 PM8/1/11
to rubyonra...@googlegroups.com
Hi, I've been trying to add default options by overriding the `to_json` method of a model thinking it would get called when sent to `render :json`. According to the documentation it should be working; from the guides:
You don’t need to call to_json on the object that you want to render. If you use the :json option, render will automatically call to_json for you.

Unless that the behavior of render is different for collections. In that case how can I do that?

In my controller I'm using:

    def index; render json: Foo.all; end

And here the overrided method:
 
    class Foo
      ...
      def to_json(options = {})
        super({methods: :rank}.merge options)
      end
    end

Calling to_json from the console work as expected. Also raising an exception from the to_json method clearly demonstrate that the to_json isn't called by render.

Thanks

Yang Yi

unread,
Aug 2, 2011, 7:30:13 AM8/2/11
to rubyonra...@googlegroups.com
try override serializable_hash

  def serializable_hash(options = nil)
    super(options.merge(:methods => :some))
  end

Reply all
Reply to author
Forward
0 new messages