alexs333
alexs333

Reputation: 12553

RABL - custom collection

I am trying to build the custom collection using RABL API. I have an Idea model that has an array of idea_actions. I need to append a custom collection of idea action using RABL, however I not seem to be able to use child :idea_actions because I need to be aware of the current action. The code below errors... Any solution how can I get the custom collection i want?

object @idea

attributes *Idea.column_names

# need access to current action
node :idea_actions do
  @idea.idea_actions.each do |action|
    { :id => action.id}
    { :custom_stuff => action.some_method } if action.something?
  end
end

# can't do that...
# child :idea_actions

Upvotes: 1

Views: 1276

Answers (1)

Harish Shetty
Harish Shetty

Reputation: 64363

I had a similar use case. This what I had to do to get this to work:

Solution 1

  • Introduce a partial for rendering the child attributes (_idea_action.rabl)

    attributes :id 
    if root_object.something?
      :custom_stuff => root_object.some_method 
    end
    
  • Modify your main view to extend the new partial

    child(:idea_actions) { 
      extends("_idea_action")
    }
    

Solution 2

node :idea_actions do
  @idea.idea_actions.map do |action|
    { :id => action.id}.tap do |hash|
      hash[:custom_stuff] = action.some_method if action.something?
    end
  end
end

Solution 3

child :idea_actions do
  attributes :id
  node(:custom_stuff, :if => lambda {|action| action.something?}) do |action|
    action.some_method
  end
end

Upvotes: 2

Related Questions