Search code examples
ruby-on-railsrubyrabl

Removing empty hashes in Rabl


In rabl I'm trying to have a child whose elements are conditional, but in the cases where to condition evaluates false it's still rendering elements which have no attributes.

Here's my .rabl:

child(:products) do
  attribute :id, :if => lambda{ |p| p.store_id == @store.id }
end

Hoping for .json that looks something like this:

"products":[{"id":2}]

But it's rendering empty values as well:

"products":[{}, {"id":2}, {}]

Is there a way I can make it so that empty elements are ignored entirely?


Solution

  • Assuming you are expecting a products method on an instance variable:

    child(@catalogue.products.select{|p| p.store_id == @store.id} => :products ) do
      attribute :id
    end