使用GET请求提交的Rails表单不会在URL中放置querystring参数



从RailsGuides Action View Form Helpers文章中工作,位于;1.1一种通用搜索形式";部分,使用此代码:

<% form_tag(search_path, :method => "get") do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>

提交此表单时,结果URL为'/search',而不是'/search?q=searchterm’,正如预期的那样。

RailsGuides的文章甚至说,

使用"获取";作为搜索表单的方法。这允许用户为特定的搜索添加书签并返回到它。更一般地说,Rails鼓励您在操作中使用正确的HTTP谓词。

但是,如果URL中不包含querystring参数,则无法为特定搜索添加书签。为什么会发生这种情况,对此可以做些什么?

尝试

`<%= form_with url: search_path, method: :get do |f| %>
<%= f.label :q, "Search for: " %>
<%= f.text_field :q %>
<%= f.submit :Submit%>
<% end %>`

form_with是一个更新的rails助手,具有rails 6

最新更新