0

I am using Rails 5 and trying to implement multiple delete functionality. Here is the form:

<%= form_tag destroy_multiple_scan_assets_path, method: :delete do %>
  <%= hidden_field_tag :asset_ids, nil, multiple: true %>
  <%= submit_tag 'Delete', class: 'btn btn-danger' %>
<% end %>

Now the hidden field value is to be set using javascript based on some checked boxes:

$('input.btn-danger').click(function() {
  var selected_asset_elements = $('input.form-check-input:checkbox:checked');
  var selected_assets_count = selected_asset_elements.length

  if (selected_assets_count == 0) {
    alert('Please select an asset to delete.')
    return false;
  } else if (confirm(`Are you sure, you want to delete ${selected_assets_count} assets?`)) {
    selected_asset_elements.each(function () {
      // Push $(this).val() in to the hidden filed value
    });
  } else {
      return false
  }
});

How do I set hidden field's value so that it's interpreted by rails as:

Parameters: {"asset_ids"=>["1", "2", "3", "4"]} 

1 Answer 1

1

You can't do that using a single hidden field, but you can have that result if you add one hidden field with name asset_ids[] for each id. That's how rails knows it has to parse the params as an array.

selected_asset_elements.each(function (el) {
  field = document.createElement('INPUT');
  field.type = 'hidden';
  field.name = 'asset_ids[]';
  field.value = el.id; #something like this
  your_form.append(field);
});

By the way, multiple is not a valid option for a hidden field, it just accepts a string value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.