简体   繁体   中英

Ruby on Rails - call Controller Method and pass Parameters to it

I have following situation:

I have a risk model and on my view it shows me a table with all risks. The table also includes a check_box_tag , as each risk should be able to be checked. In the tablehead there is a button and if this button is clicked, a method of the risk controller should be called, and it should have all checked risk IDs as parameter.

Actually, I don't know which would be the best way to solve this.

I have following code so far:

View:

<table>
  <thead>
    <tr>
      <th>Risk Name</th>
      <th>
        <button id="mergerisks">Merge Risks</button>
      </th>
    </tr>
  </thead>
  <tbody>
     <% Risks.all.each do |risk| %>
        <tr>
          <td><%= risk.name %></td>
          <td><%= check_box_tag 'mergerisks', risk.id %>
          </td>
        </tr>
     <% end %>
 </tbody>
</table>

Javascript:

  $( "#mergerisks" ).on( "click", function() {
    var selectedriskmerge = new Array();
    $("input:checked").each(
      function() {
        selectedriskmerge.push($(this).val());
    });
  });

Edit Added the following ajax call to javascript

$.ajax({
  url: '/riskmerge',
  data:selectedriskmerge,
  success:function() {
  window.alert("Success!");
  }
});

For now the Button only triggers the Javascript, and there are the ID's of all checked Risks are stored in an array.

But now I don't know what would be the best way to call a controller method in the risk controller and pass the IDs of all checked Risks to the method.

Thanks for any help.

NOTE: This is slightly different from what you wanted, but might provide a better user experience since they won't have to click an additional button at the end to update the records so heed with caution. No matter what though you will get a decent example of how to use ajax for your own needs.

First you need to create an action in the controller that updates the record you want which you already have. The twist is that instead of rendering html you will want to render json at the end. Something like this will do.

if risk.update_attribute(check: true)
  render :json => { status: "Everything worked!"}
else
  render :json => { status: "Something went wrong!"}
end

Next you will want to set up the javascript so that when a check box is clicked, an ajax post is sent to the action that updates the record. You have this partially done with your javascript. Inside your click event, you can have something like

$.post("/risk_update", 
      // This line below is the parameters sent to the action. 
      //So your action will recognize params[:risk_id]
      { risk_id: $(".clicked_check_box").attr("value") },
      "json")
      .done(function (responseText) {
        if (responseText.status === "Everything worked!") {
          // Do something on success of info being saved
        } else if (responseText.status === "Something went wrong!") {
          // Do something on failure of info being saved
        }
      });

Finally, there is a problem with the check box. Do you want the user to uncheck the box and call a record again. This of course goes beyond the discussion of the question but they are some things you have to keep in mind.

Of course in your case you will want to click a button that grabs all the ids and sends them to the action to update the records. One way would be to have javascript inject the id into an array when a check box is marked, then when the user clicks on the submit button the array is sent as params to the action that then loops through the arrays and updates the risks.

I'm sure there are better ways though, that's just the first thing that came to mind.

Your best bet would be to place all of the check boxes inside of a form.

<%= form_tag controller_method_name_your_controller_path, :method => 'get', do %>
    ...
    <%= submit_tag 'submit' %>
<% end %>

Declare the path in the routes.rb file under your_controller

get :controller_method_name

You can group you check boxes together by using check_box :

<%= check_box 'mergerisks', risk.id %>

Then using params[:mergerisks] in the controller will return a hash with risk.id as the keys and a 1 or 0 depending on if the check box is checked.

Some documentation on routes and forms:

http://guides.rubyonrails.org/routing.html

http://guides.rubyonrails.org/form_helpers.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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