Question

According to the RABL documentation under "Child nodes", the following is possible:

object @user
child :posts do |user|
  attribute :title unless user.suspended?
end

This implies that the user variable yielded by the block is the parent object @user.

However, when I attempt the following:

collection @listings
child :address do |listing|
  attribute :number_and_street unless listing.address_hidden?
end

I get a NoMethodError:

undefined method `address_hidden?' for #<Address:0x007fb83d6eaf80>

meaning that the block is yielding the child address object instead of the parent @listing object, as implied by the documentation.

The only way around this that I can see is something like address.listing.address_hidden?, which would result in way too many database queries, so I'd like to avoid that.

Am I doing something wrong? Is there any way to fix this behavior?

Was it helpful?

Solution

When you use collection the child block does not yield the individual objects. What I would do is split it in two files.

index.json.rabl

collection @listing
extends "app/view/listings/base"

base.json.rabl

object @listing
child :address do |listing|
  attribute :number_and_street unless listing.address_hidden?
end

EDIT: I just noticed you're using the rabl-rails gem. My solution works for 'rabl', I am not too sure about this gem :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top