as_json not calling as_json on associations as_json not calling as_json on associations json json

as_json not calling as_json on associations


This is a known bug in Rails. (The issue is marked closed due to the migration to Github issues from the previous bug tracker, but it's still a problem as of Rails 3.1.)


As acknowledged above, this is an issue with the Rails base. The rails patch here is not yet applied and seems at least slightly controversial, so I'm hesitant to apply it locally. Even if applied as a monkey patch it could potentially complicate future rails upgrades.

I'm still considering RABL suggested above, it looks useful. For the moment, I'd rather not add another view templating language into my app. My current needs are very small.

So here's a workaround which doesn't require a patch and work for most simple cases. This works where the association's as_json method you'd like to have called looks like

def as_json(options={})  super( <... custom options ...> )end

In my case I've got Schedule model which has many Events

class Event < ActiveRecord::Base  # define json options as constant, or you could return them from a method  EVENT_JSON_OPTS = { :include => { :locations => { :only => [:id], :methods => [:name] } } }  def as_json(options={})    super(EVENT_JSON_OPTS)  endendclass Schedule < ActiveRecord::Base  has_many :events  def as_json(options={})    super(:include => { :events => { Event::EVENT_JSON_OPTS } })  endend

If you followed the guideline that anytime you :include an association in your as_json() methods, you define any options you need as a constant in the model to be referenced, this would work for arbitrary levels of associations. NOTE I only needed the first level of association customized in the above example.


I've found that serializable_hash works just as you'd expect as_json to work, and is always called:

  def serializable_hash(options = {})    result = super(options)    result[:url] = "http://.."    result  end