I'm kinda new to the whole rails/ruby thing. I've built a restful API for an invoicing app. Summary of models is below.
class Invoice < ActiveRecord::Base
has_many :pages
end
class Page < ActiveRecord::Base
belogs_to :invoice
has_many :rows
end
class Row < ActiveRecord::Base
belogs_to :page
end
I would like to be able to include related models in one rest call. I can currently do one level of nesting. For example i can get an Invoice with all its pages /invoices?with=pages is the call i would make. In controller i would create a hash array from this as per below(probably not the best code you've seen):
def with_params_hash
if(params[:with])
withs = params[:with].split(',')
withs.map! do |with|
with.parameterize.underscore.to_sym
end
withs
else
nil
end
end
This will return a hash as array e.g [:pages]
In the controller i use it as
@response = @invoice.to_json(:include => with_params_hash)
This works fine. I would like to be able to include nested models of say page.
As you know this can be done this way:
@invoice.to_json(:include => [:page => {:rows}])
The first question i guess is how do i represent this in the URL? I was thinking: /invoices?with=pages>rows. Assuming thats how I decide to do it. How do i then convert with=pages>rows into [:pages => {:rows}]
invoices/3/pages/5/rows- resource/id/resource/id/resource for lists and resource/id/resource/id for individual resources. Or just resource/id of course, depending on the problem. Also, see here: asciicasts.com/episodes/230-inherited-resources for something which may or may not help, but should give an idea of a Rails-ey way of handling nested resources.invoices/3/pages,invoices/3/pages/5/rowsand so forth. The reason i wanted to do this is so i can reduce overhead and minimise api calls. Cause if an invoice had 5 pages with 10 rows each. I'd have to make 5 More calls plus another 5 to get rows. I'd like to get everything at one go. Hope that helps.