如何在rabl模板中的子元素中添加父属性(当父元素是数组时)?

时间:2013-04-08 11:53:18

标签: ruby-on-rails json rabl

如何在rabl模板中的子项中添加父属性?要做这样的事情:

  some_root_attr: {
    attr_a: 'rgtr',
    parent: [
      {
        attr_1: 'asd',
        child: {
          attr_3: 6,
          attr_from_parent_array_member: 'cvb'
        }
      },

      {
         attr_1: 'ert',
         child: {
           attr_3: 9,
           attr_from_parent_array_member: 'erty'
         }
      },
      ...
  ]
}

如何在父数组成员的子进程中获取父数组成员?

2 个答案:

答案 0 :(得分:0)

object @obj
attributes :attr_a

child :parents do
  attributes :attr_1
  parent = root_object.dup
  child :child do 
    attributes :attr_3
    node(:attr_from_parent_array_member) { parent.attr_from_parent_array_member }
  end
end

NB尚未测试

答案 1 :(得分:0)

nesquena在github上发布了解决方案: https://github.com/nesquena/rabl/issues/436

collection @posts

node :categories do |p|
  p.categories.map do |c| 
    partial("categories/show", :object => c).merge(:post_attr => p.post_attr)
  end
end