nesquena / rabl

General ruby templating with json, bson, xml, plist and msgpack support
http://blog.codepath.com/2011/06/27/building-a-platform-api-on-rails/
MIT License
3.64k stars 334 forks source link

How to get parent object in child block when parent is part of collection #651

Open waggl opened 8 years ago

waggl commented 8 years ago

I have a template like this (have made generic):

collection @posts

post_as_root_object = root_object

child(:commenters) do |post|
  node(:position) do |commenter|
    commenter.position(post)
  end
end

Posts have many Commenters and Commenters have many Posts. The position method needs the post it is related to passed in (I know the example is a little contrived).

I can't figure out how to get the post that is currently being rendered. Passing a variable into the child block gives me the commenters collection (https://github.com/nesquena/rabl/issues/393), and post_as_root_object is the posts collection.

How do I access the specific post that is being rendered in the position node?

drewB commented 8 years ago

I made this issue request (accidentally logged in with our company's github). We were able to solve this with the following:

collection @posts

node(:commenters) do |post|
  post.commenters.map do |commenter|
    partial('posts/commenter', object: commenter, locals: {post: post})
  end
end

-------

#posts/commenter.rabl

object commenter
node(:position) do |commenter|
  commenter.position(locals[:post])
end

Would be great if there was a more elegant solution.