【问题标题】:Why can't form_tag and form_for be used in helper functions [Rails]为什么不能在辅助函数中使用 form_tag 和 form_for [Rails]
【发布时间】:2018-07-17 15:55:15
【问题描述】:

我正在做一个 Rails 项目,我正在重构一些代码。因为我使用与 form_tag 相同类型的 collection_select,所以我决定为它创建一个助手,我只需更改路径和请求。

但是,我注意到当我在辅助函数中使用 form_for 时,它只返回最后一行。在下面的例子中,它只会返回提交按钮,如果我删除提交按钮,它只会返回选择。

def form_select #### Helper Function
     form_tag po_path(@pos), method: "get" do 
         collection_select :po, :category, @pos.categories.order(:id), :id, :name, selected: (@items.empty? ? "" : @items.first.category.id)
         submit_tag "Show items" 
     end 
  end 
end 

我的问题是;为什么这不起作用,但下面的呢?

<!-- In the view -->
<%= form_tag po_path(@pos), method: "get" do %> 
        <%= collection_select :po, :category, @pos.categories.order(:id), :id, :name, selected: (@items.empty? ? "" : @items.first.category.id)%> 
        <%= submit_tag "Show items" %> 
    <% end %>

form_for 也是如此。

有人知道为什么会这样吗?

【问题讨论】:

  • 因为它返回方法执行的最后一条语句,也为了代码的可重用性你可以创建部分
  • 由于 form_for/tag 是块,我认为它会返回一个被 ruby​​ 解释为 html 表单的对象。辅助函数不会返回那个 vlbe 吗?如果它只返回最后一行,为什么它会在视图中显示所有内容?
  • form_for/tag 不是块——它们是由 Rails 助手定义的方法。您将块传递给在&lt;form&gt;&lt;/form&gt; 之间生成的助手。这些块将返回最后一个表达式的结果,就像 ruby​​ 中的其他所有内容一样。
  • 啊,我明白了;我把这个概念搞混了。谢谢。

标签: ruby-on-rails ruby frontend


【解决方案1】:

在帮助方法中调用表单帮助程序(或任何其他 html 帮助程序)时,您需要调用 concat(或手动连接字符串)。

def form_select #### Helper Function
  form_tag po_path(@pos), method: "get" do 
    concat collection_select :po, :category, @pos.categories.order(:id), :id, :name, selected: (@items.empty? ? "" : @items.first.category.id)
    concat submit_tag "Show items" 
  end 
end 

这是因为帮助程序没有像您期望的那样返回连接的 html 字符串。相反,块返回最后一个表达式的结果,就像任何其他 Ruby 块一样。

def foo(&block) 
  yield
end

# returns "baz"
foo do
  "bar"
  "baz"
end

它在 ERB 中工作,因为 &lt;%= %&gt; are expressions 在渲染模板时,渲染器应该用代码的结果(作为字符串)替换代码元素。这有点像puts,但它写入模板缓冲区。

<%= foo do %>
  <%= "bar" %> <%= "baz" %>
<% end %>

此示例将向模板输出“bar baz”。

但是你真的应该考虑在这里使用部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2013-08-12
    • 1970-01-01
    相关资源
    最近更新 更多