Let us say I have a model Post which belongs to a User. To convert to json, I do something like this
@reply.to_json(:include => {:user => {:only => [:email, :id]},
:only => [:title, :id])
However, I want to set some defaults for this so I don't have to specify :only everytime. I am trying to override as_json to accomplish this. When I add as_json in User model, it is called when I do @user.to_json but when user is included in @reply.to_json, my overriden as_json for User is ignored.
How do I make this work?
Thanks
You can do this by overriding serializable_hash
in your model, like so:
class Reply < ActiveRecord::Base
def serializable_hash(options={})
options = {
:include => {:user => {:only => [:email, :id]},
:only => [:title, :id]
}.update(options)
super(options)
end
end
This will affect all serializable methods, including serializable_hash
, to_json
, and to_xml
.
In the Reply model:
def as_json(options = {})
super options.merge(:methods => [:user], :only => [:id, :title])
end
And in the User model:
def as_json(options = {})
super options.merge(:only => [:id, :email])
end
When the association is included as a method and not an include, it will run the .to_json on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With