2015-10-05 53 views
1

我想要得到以下的工作 - 基本上,按钮提交给searchable_controller索引操作,并应该将params [:search_task]传递给它。但由于某种原因,它不起作用。Rails 4:button_to不提交参数

  <div class="btn-group InterestGroup" role="group" aria-label=""> 
      <button class = "btn btn-success InterestStatButton"><%= User.tagged_with(interest, :on => :tags, :any => true).count %></button> 
      <%= button_to interest, searches_path, :method => :get, :class => "btn btn-default InterestLabelButton" %> 
      <%= hidden_field_tag :search_task, interest, :id => "search", :class => "form-control" %> 
      </div> 

在头文件的同一页上,我在头文件中做了相同的事情,并且工作正常。我不明白,如果你看一下HTML中的每个代码,第一个代码块中的隐藏字段与第二个代码块中的form_tag中的输入相同。

  <%= form_tag searches_path, html: {class: "navbar-form navbar-left"}, :method => :get do %> 
       <div class="form-group" style="display:inline;"> 
        <div class="input-group" style="display:table; width:350px;"> 
        <span class="input-group-addon" style="width:1%;"><span class="glyphicon glyphicon-search"></span></span> 
        <%= text_field_tag :search_task, nil, class: "form-control", id: "search", placeholder: "Search for members or content", label: false %> 
        </div> 
       </div> 
      <% end %> 

回答

1

的问题是,button_to是一个自包含的方法(IE不能传递块等):

生成一个包含一个按钮用于提交由所述创建的URL 一个形式选项集。

当你使用:

<%= button_to interest, searches_path, :method => :get, :class => "btn btn-default InterestLabelButton" %> 
<%= hidden_field_tag :search_task, interest, :id => "search", :class => "form-control" %> 

...它根本不会被添加到形式,因此将不会被通过。


How to add additional params to a button_to form?

你需要什么是对search_task PARAM添加到您的button_to帮手:

<%= button_to interest, searches_path, method: :get, class: "btn btn-default InterestLabelButton", params: { search_task: interest } %> 

button_to形式发送默认为POST请求。这将掩盖通过的参数;如果你想使用GET,你做了正确的事情并宣布它。需要注意的是,GET请求会将PARAMS附加到请求URL。

您可以在这里阅读更多关于它的信息:http://www.w3schools.com/tags/ref_httpmethods.asp

+1

完美。一个编辑...... <%= button_to interest,searching_path,method :: get,class:“btn btn-default InterestLabelButton”,params:{search_task:interest}%> – GhostRider

+0

谢谢 - 修改了代码 –