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:
https://github.com/josevalim/active_model_serializers
That is what is going to be used in Rails 4.
If you want Hypermedia (links to resources, etc.), HAL support, etc. to be
more REST-driven, check out roar-rails, but note that adoption is not that
heavy yet: https://github.com/apotonick/roar-rails
Prior to those, a good option was RABL, and it is still a good option for
some probably, although I''m not sure what it can do that you''d
want over
active_model_serializers: https://github.com/nesquena/rabl
I spent a good amount of time wrangling with as_json and overriding it on
ActiveModel::Base like:
https://github.com/garysweaver/restful_json/blob/a20e835133cacdad4bfc4de8dda9e5e0b895b1bb/lib/restful_json/model.rb
And to answer your question- methods is a good way of including
associations and whatever else you want to define that can be calculated on
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.
On Friday, September 28, 2012 2:40:52 PM UTC-4, Ruby-Forum.com User
wrote:>
> Hi,
>
> 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]}}])
> end
>
>
> Thanks.
>
> -Ari
>
> --
> Posted via http://www.ruby-forum.com/.
>
--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To view this discussion on the web visit
https://groups.google.com/d/msg/rubyonrails-talk/-/M4P6x1KQul8J.
For more options, visit https://groups.google.com/groups/opt_out.