【问题标题】:Problem with returning values from a helper method in Rails从 Rails 中的辅助方法返回值的问题
【发布时间】:2010-04-13 20:13:44
【问题描述】:

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

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

我在products_helper.rb中写了一个辅助方法,基于this question的回答。

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

但这并没有按预期工作。它只返回最后一个节点——最后一个&lt;td&gt;123&lt;/td&gt;

我应该怎么做才能让它工作?

【问题讨论】:

    标签: ruby-on-rails return-value helpermethods


    【解决方案1】:

    记住函数 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 的末尾加上一个加号即可。

    【讨论】:

    • 如果我在 2 个content_tags 之间添加一个+,我会得到一个Internal Server Errorsyntax error, unexpected tSYMBEG, expecting kDO or '{' or '('
    • 我在 content_tagdo-end 周围添加了括号,并在其他人的参数周围添加了括号:(content_tag :tr do content_tag(:td, ...)+content_tag(:td, ...) end) + (content_tag :tr do ... end)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    相关资源
    最近更新 更多