nesquena / rabl

General ruby templating with json, bson, xml, plist and msgpack support
http://blog.codepath.com/2011/06/27/building-a-platform-api-on-rails/
MIT License
3.64k stars 334 forks source link

Exclude child(ren) when not present in query #646

Open oseintow opened 8 years ago

oseintow commented 8 years ago

I'm generating JSON with Rabl but I can't find a way to eliminate children when not included in query. The issue am facing is am generating the json based on query_strings.

for example. with this url http://localhost:3000/products.json i generate the following query

@products = @product.all

but with url http://localhost:3000/products.json?with=product_variants i generate

@products = @product.includes(:product_variants)

and with http://localhost:3000/products.json?with=product_variants.labels i generate

@product = @product.includes(:product_variants => :labels).

and it goes on and on and on http://localhost:3000/products.json?with=product_variants.labels..........

The issue is if the last url is accessed rabl generate the json without any N + 1 query problems because it queries all related association.

but when the first two url's are accessed i get the N + 1 problem meaning it queries the nested association which i don't want to. And moreover if there are no query strings i don't want to load the nested associations

Is there a way to dynamically include/exclude the nested association/child if they are included or excluded in the query.

Been trying and googling this for days but no solution. Any help will be appreciated. Thank you.