4

我有一个如下所示的 RABL 模板

object @user
attributes :name
child :contacts do
  # does not work
  if contact.is_foo?
    attributes :a1, :a2
  else
    attributes :a3, :a4
  end
end

如何访问模Contact板块中的对象child?我需要对子实例执行一些条件逻辑。

4

4 回答 4

10

您可以通过声明块参数来访问当前对象。

object @user
attributes :name
child :contacts do |contact|
  if contact.is_foo?
    attributes :a1, :a2
  else
    attributes :a3, :a4
  end
end

旧答案

我最终使用了root_object 方法,它返回给定上下文中的数据对象。

object @user
attributes :name
child :contacts do
  if root_object.is_foo?
    attributes :a1, :a2
  else
    attributes :a3, :a4
  end
end
于 2012-05-24T06:24:27.323 回答
3

另一种保持干燥的方法:

联系人/show.json.rabl

object @contact
node do |contact|
    if contact.is_foo?
        {:a1 => contact.a1, :a2 => contact.a2}
    else
        {:a3 => contact.a3, :a4 => contact.a4}
    end
end

用户/show.json.rabl

object @user
attributes :name
child :contacts do
    extends 'contacts/show'
end
于 2012-06-21T00:54:27.620 回答
1

这是一种方法:

child :contacts do
  node(:a1, :if => lambda { |c| c.is_foo? }
  node(:a2, :if => lambda { |c| c.is_foo? }

  node(:a3, :unless => lambda { |c| c.is_foo? }
  node(:a4, :unless => lambda { |c| c.is_foo? }
end

不完全相同,但一种可能性,另一种是:

node :contacts do |u|
  u.contacts.map do |c|
    if contact.is_foo?
      partial("contacta", :object => c)
      # or { :a1 => "foo", :a2 => "bar" }
    else
      partial("contactb", :object => c)
      # or { :a3 => "foo", :a4 => "bar" }
    end
  end
end
于 2012-05-24T02:13:12.683 回答
0

我知道这是一个迟到的回复,但遇到了类似的问题,所以想回答。

它更像是一个黑客,但有效。

当两个变量用作块参数contact和一个随机变量x时,contact指的是集合的一个对象

在块参数中使用一个变量时,它会呈现集合对象

object @user
attributes :name
child :contacts do |contact, x|
  if contact.is_foo?
    attributes :a1, :a2
  else
    attributes :a3, :a4
  end
end
于 2016-01-29T08:06:20.053 回答