简体   繁体   English

Rails link_to 或 button_to 发布带有参数的请求

[英]Rails link_to or button_to post request with parameters

I have a restful (scaffold generated) controller and model for Votes, I am simply trying to add a field into the view that when clicked, will create a new vote for a given car.我有一个安静的(脚手架生成的)控制器和投票模型,我只是想在视图中添加一个字段,当点击时,将为给定的汽车创建一个新的投票。 It needs to be a POST, What's the way I should be doing this in rails?它需要是一个 POST,我应该在 Rails 中执行此操作的方式是什么?

<% @cars.each do |car| %>
  <tr>
    <td><%= button_to '+', {:controller => "votes", :action => "create"}, :car_id => car.id, :user_id=> session[:user_id] , :method=>:post  %></td>
    <td><%= car.votes.count %></td>
    <td><%= car.name %></td>
    <td><%= car.code %></td>
    <td><%= car.album %></td>
<% end %>
<td><%= button_to '+', {:controller => "votes", :action => "create", :car_id => car.id, :user_id=> session[:user_id]} , :method=>:post  %></td>

这将使 params[:car_id] 和 params[:user_id] 在 VotesController 创建操作中可用。

Rails 5 + haml, for example: Rails 5 + haml,例如:

= button_to "smth", some_path, method: :get, params: { start_point: 3.month.ago }

the key is to use params key, then in controller you will be able to get value via @some_var = params[:start_point]关键是使用params键,然后在控制器中,您将能够通过@some_var = params[:start_point]获取值

<td><%= button_to '+', {:controller => "votes", :action => "create", :car_id => car.id, :user_id=> session[:user_id]} , {:method=>:post}  %></td>

Erez is right -- the first hash in this case is the "URL parameters" hash, which controls the URL where the button sends its request. Erez 是对的——在这种情况下,第一个散列是“URL 参数”散列,它控制按钮发送请求的 URL。 The second hash is the "HTML parameters" hash, which controls the appearance of the button, as well as the submit method (by adding a hidden field in the generated HTML).第二个散列是“HTML 参数”散列,它控制按钮的外观,以及提交方法(通过在生成的 HTML 中添加一个隐藏字段)。

The confusing thing here is that the URL parameters ask you to specify the controller and action in a controller-centric way, but then requires you to pass along the id's for the URL, which is more URL-centric.这里令人困惑的是,URL 参数要求您以以控制器为中心的方式指定控制器和操作,但随后要求您传递 URL 的 id,这更以 URL 为中心。 That combination threw me off for a long time.这种组合让我失望了很长时间。 You can add any additional parameters you like in the URL parameters hash, by the way -- to use as arguments for other methods in your controller, to take more advanced action.顺便说一下,您可以在 URL 参数散列中添加您喜欢的任何其他参数 - 用作控制器中其他方法的参数,以执行更高级的操作。

You can also pass your parameters as an argument to your path helper like so您还可以像这样将参数作为参数传递给路径助手

<%= button_to '+', votes_path(car_id: card.id), method: 'post'  %>

You can fetch your session id from your controller or still pass it to the paths helper if you want.如果需要,您可以从控制器获取会话 ID,也可以将其传递给路径助手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM