Ruby on Rails Monday, August 1, 2011

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

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/8ny2QVI8gAoJ.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment