Rails link_to or button_to post request with parameters

前端 未结 4 508
悲哀的现实
悲哀的现实 2020-12-24 06:52

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 c

相关标签:
4条回答
  • 2020-12-24 07:36
    <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. 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).

    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. 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.

    0 讨论(0)
  • 2020-12-24 07:39

    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.

    0 讨论(0)
  • 2020-12-24 07:41
    <td><%= button_to '+', {:controller => "votes", :action => "create", :car_id => car.id, :user_id=> session[:user_id]} , :method=>:post  %></td>
    

    This will make params[:car_id] and params[:user_id] available in VotesController create action.

    0 讨论(0)
  • 2020-12-24 07:50

    Rails 5 + haml, for example:

    = 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]

    0 讨论(0)
提交回复
热议问题