Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally include child nodes with RABL

I think I have a very basic case when I'm using rabl to return JSON for standard RESTful controller methods...

First let's say I have a typical one to many relationship with parent and child (let's say customer and accounts):

class Customer < ActiveRecord::Base
  has_many :accounts
end

In my controller for customer I have index and edit - index where I just want to return all Customers (WITHOUT accounts) and edit where I want to return a specific Customer with all of their Accounts. With index I don't want to return the accounts for obvious performance (N+1) reasons.

In my rabl, I have the following:

#index.rabl (for listing all customers)
collection :@customers
extends "customers/_customer"

and

#edit.rabl (for editing a single customer)
object :@customer
extends "customer/_customer"

I am reusing the _customer.rabl for both the index and the edit.

#_customer.rabl
object :@customer
attributes :name, ......

if @include_accounts
  child :accounts do
    extends "accounts/_account"
  end
end

I set the @include_accounts in my edit (controller) and not the index - but this doesn't work - essentially the instance var here (@include_accounts) never gets passed down. What is the correct pattern to implement this?

like image 336
Arthur Frankel Avatar asked Mar 27 '13 02:03

Arthur Frankel


1 Answers

Even though the rails-rabl gem claims it is faster, I found that templates aren't as flexible for conditional expressions - see rabl-rails readme re: instance variables.

like image 196
Mark Nadig Avatar answered Oct 31 '22 16:10

Mark Nadig