Reputation: 783
I already know how to include the relationships of has_many & has_one relationships into my JSON rendering. I even know how to exclude certain attributes when doing so. For those that don't know here's a good post:
Rails Object Relationships and JSON Rendering
However, what I don't know how to do is have it use the as_json on the child object so I don't have to redeclare it on every parent relationship.
So if I have something like this...
class Customer < ActiveRecord::Base
has_many :orders
def as_json(options={ })
super({ :except => :Password, :include => [:orders] }.merge(options))
end
end
class Order < ActiveRecord::Base
has_one :customer
def as_json(options={ })
super({ :include => [:customer] }.merge(options))
end
end
It ends up sending back the Customer password when you view it from the Order perspective.
Ideally I'd want it to follow the rules of the as_json defined in the model so I don't have to put in exceptions for the inclusion of :customer on every child object.
P.S. - This is just an example not a real world scenario.
Upvotes: 3
Views: 1279
Reputation: 46703
I would encourage you to use the RABL gem versus overriding as_json
for all of your models. It's much easier to define your JSON responses using only the parameters / relationships you want. You can also easily create parent/children nesting.
https://github.com/nesquena/rabl
Upvotes: 2