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

users / show.json.rabl

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

これが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

まったく同じではありませんが、1つの可能性、別の可能性は次のとおりです。

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

返信が遅いことは承知していますが、同様の問題に遭遇したので、答えることを考えました。

それはハックのようなものですが、機能します。

2つの変数がブロック引数の連絡先と確率変数xとして使用される場合、連絡先はコレクションのオブジェクトを参照します

ブロック引数で1つの変数を使用すると、コレクションオブジェクトがレンダリングされます

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 に答える