1

content_tag メソッドを使用して、Ruby on Rails でテーブルを構築しようとしています。

これを実行すると:

def itemSemanticDifferential(method, options = {})

  if options[:surveyQuestion].any? then
    @template.content_tag(:tr) do
      @template.content_tag(:td, options[:surveyQuestion], :colspan => 3)
    end
  end

  @template.content_tag(:tr) do
    @template.content_tag(:th, options[:argument0])
  end
end

2 番目の部分のみがレンダリングされます。

@template.content_tag(:tr) do
  @template.content_tag(:th, options[:argument0])
end

これがなぜなのか誰か教えてもらえますか?

4

1 に答える 1

4

Ruby Railsは、returnが明示的に呼び出されない場合、最後に使用した変数を返します。( 例: )

def some_method(*args)
  a = 12
  b = "Testing a String"
  # ...
  3
end # This method will return the Integer 3 because it was the last "thing" used in the method

配列を使用してすべてのcontent_tagを返します(警告:このメソッドは、期待どおりにcontent_tagではなく配列を返します。ループする必要があります):

def itemSemanticDifferential(method, options = {})

  results = []

  if options[:surveyQuestion].any? then
    results << @template.content_tag(:tr) do
      @template.content_tag(:td, options[:surveyQuestion], :colspan => 3)
    end
  end

   results << @template.content_tag(:tr) do
    @template.content_tag(:th, options[:argument0])
  end

  return results # you don't actually need the return word here, but it makes it more readable
end

質問の作成者からの質問によると、結果はcontent_tagsの配列であるため、結果をループする必要があります。.html_safeまた、 content_tagsを(文字列ではなく)HTMLとして出力するためにを使用する必要があります。

<% f.itemSemanticDifferential(:method, options = {}).each do |row| %>
  <%= row.html_safe %>
<% end %>
于 2012-12-05T17:14:58.260 に答える