Search code examples
htmlruby-on-railsrubyhtml-tablecontent-tag

Odd rendering of an html table in Ruby on Rails when using content_tag


I'm trying to build a table in Ruby on Rails with the help of the content_tag method.

When I run this:

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

Only the second part gets rendered:

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

Can anyone tell me why this is?


Solution

  • Ruby Rails returns the last variable it used if no return is explicitly called. ( example: )

    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
    

    Use an Array to return all the content_tag (WARNING: this method will return an Array, not a content_tag as you expect, you'll need to loop on it):

    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
    

    As asked by author of the Question, You need to loop on the result because it is an array of content_tags. Also, you need to use .html_safe to output the content_tags as HTML (not strings).

    <% f.itemSemanticDifferential(:method, options = {}).each do |row| %>
      <%= row.html_safe %>
    <% end %>