3

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.

Community
  • 1
  • 1
Altonymous
  • 783
  • 7
  • 25

1 Answers1

2

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

iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
  • How do you dynamically change the output using rabl? Sometimes I want to change what is returned in the json based on whom is requesting the data. – Altonymous Dec 27 '11 at 22:34
  • You use the same Ruby syntax as you normally would (i.e. `if` and `unless` statements among other things). – iwasrobbed Dec 27 '11 at 22:52