How to Include Associations in #as_json


Does anyone know how to include nested associations when overriding a
model’s #as_json method?

Below is my attempt to include direct and nested associations.

NOTE: “office” is a direct association, “company” is nested association
via “office”. I’d like both included in the generated json output.

def as_json(options={})
super(:include => [{:office => {:only => [:company, :street, :city,
:state, :zip_code]}}])



to_json and as_json are not what you are probably looking for.

If you are using a decently up-to-date version of Rails, look at:

That is what is going to be used in Rails 4.

If you want Hypermedia (links to resources, etc.), HAL support, etc. to
more REST-driven, check out roar-rails, but note that adoption is not
heavy yet:

Prior to those, a good option was RABL, and it is still a good option
some probably, although I’m not sure what it can do that you’d want over

I spent a good amount of time wrangling with as_json and overriding it
ActiveModel::Base like:

And to answer your question- methods is a good way of including
associations and whatever else you want to define that can be calculated
the model. But, please don’t use as_json unless you really need to.

Note: Mass assignment security (attr_accessible/attr_protected) is going
away in Rails 4. Also, there is a lot wrong with the implementation that
I’d developed that I’m trying to fix now.

Good luck.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs