Search code examples
ruby-on-railsrubyrabl

Accessing the child instance in a RABL template


I have a RABL template as shown below

object @user
attributes :name
child :contacts do
  # does not work
  if contact.is_foo?
    attributes :a1, :a2
  else
    attributes :a3, :a4
  end
end

How do I access the Contact object in the child block of the template? I need to perform some conditional logic on the child instance.


Solution

  • You can access the current object by declaring the block parameter.

    object @user
    attributes :name
    child :contacts do |contact|
      if contact.is_foo?
        attributes :a1, :a2
      else
        attributes :a3, :a4
      end
    end
    

    Old answer

    I ended up using the root_object method, which returns the data object in a given context.

    object @user
    attributes :name
    child :contacts do
      if root_object.is_foo?
        attributes :a1, :a2
      else
        attributes :a3, :a4
      end
    end