在RABL模板中访问子实例

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

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

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

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

 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 

保持干燥的另一种方法:

联系人/ 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 

这是一种方式:

 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 

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

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

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

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

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