Conditionally include child nodes with RABL
Asked Answered
T

1

6

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?

Tonguelash answered 27/3, 2013 at 2:49 Comment(1)
Which version of the gem are you using, rabl or rabl-rails?Handal
S
3

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.

Stereochromy answered 30/3, 2013 at 17:52 Comment(1)
Thank you. I switched to the rabl gem and everything worked like a charm.Tonguelash

© 2022 - 2024 — McMap. All rights reserved.