我想在每个对象有 2 行的表中打印一些对象,如下所示:

<tr class="title">
    <td>Name</td><td>Price</td>
</tr>
<tr class="content">
    <td>Content</td><td>123</td>
</tr>

我写了一个辅助方法 products_helper.rb, ,基于答案 这个问题.

def write_products(products)
  products.map {
    |product|
    content_tag :tr, :class => "title" do
      content_tag :td do
        link_to h(product.name), product, :title=>product.name
      end
      content_tag :td do
        product.price
      end
    end
    content_tag :tr, :class => "content" do
      content_tag :td, h(product.content)
      content_tag :td, product.count
    end
  }.join
end

但这并没有按预期工作。它只返回最后一个节点 - 最后一个 <td>123</td>

我应该做什么才能让它发挥作用?

有帮助吗?

解决方案

请记住,函数 content_tag 返回一个字符串。它不直接写入页面。所以你对 TD 所做的事情是这样的:

content_tag :tr do
  content_tag :td do
    link_to h(product.name), product, :title=>product.name
  end
  content_tag :td do
    product.price
  end
end

如果我们部分评估这将是

content_tag :tr do
  "<td title='Ducks'> <a ...>Ducks</a></td>"
  "<td>19</td>"
end

在一个块中,最后一个值是返回的值。存在两个字符串,但第一个字符串消失在以太中。第二个字符串是块中的最后一个值并被返回。

您需要做的是在它们之间放置一个 + 将字符串添加在一起:

content_tag :tr do
  (content_tag(:td) do
    link_to h(product.name), product, :title=>product.name
  end) + #SEE THE PLUS IS ADDED HERE
  (content_tag(:td) do
    product.price
  end)
end

您必须在 TR 级别执行相同的操作,只需在第一个 content_tag 末尾后添加一个加号即可。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top