samedi 2 juillet 2016

Rails form_tag and check_box_tag array for collection of selected objects

Long time lurker but haven't posted yet. Despite hours of debugging I can't seem to figure out why my check_box_tag won't pass an array. Essentially I would like the check box behaviour to allow the user to select multiple records and then use a button to either discontinue or refill the record.

View:

<% @medications.each do |medication| %>     
  <div class="small-4 columns three-column">    
    <%= link_to medication.drug_name, edit_medication_path(medication), remote: true  %>            
  </div>
  <div class="small-3 columns three-column">
    <%= link_to medication.duration, edit_medication_path(medication), remote: true %>
  </div>
  <div class="small-3 columns three-column">
    <%= link_to medication.duration_unit, edit_medication_path(medication), remote: true %>
  </div>
  <div class="small-2 columns three-column"> 
    <%= form_tag(medication_select_path, method: 'put', :id => 'medication-select') do %>
      <%= check_box_tag "medications[]", medication.id  -%>
    <% end %>
  </div>
<% end %>

<div class="small-6 columns">
  <%= submit_tag "Discontinue", :type => 'submit', :class => 'hollow alert button', :form => 'medication-select', :value => 'Discontinue', method: 'put' %>
</div>
<div class="small-6 columns">
  <%= submit_tag "Refill", :type => 'submit', :class => 'hollow create button', :form => 'medication-select', :value => 'Refill', method: 'put' %>
</div>

Controller:

@selected_meds = Medication.find(params[:medications])

When I look at terminal after pressing the submit button I get an output with only the first medication.id listed in params despite selecting 4 records.

Terminal:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"aNWTazi45CLxMA", "medications"=>["44"], "commit"=>"Discontinue"}

Also my output HTML appears to be correct when viewing source:

<form id="medication-select" action="/medication_select" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="_method" value="put" /><input type="hidden" name="authenticity_token" value="DpJ8" />
<input type="checkbox" name="medication_id[]" id="medication_id_" value="44" />

I've tried multiple sources (and copied the code as clearly as possible) but still have been unable to get an array coming up in params ids.

http://ift.tt/29dnsZk http://ift.tt/1tNw4Uz

As expected from the terminal output I'm getting the expected changes to medication with id=44 but if I check medication with ids of 44, 46, 50 it only performs the controller action on the first checked id.

The only thing I can think of is that maybe splitting up my submit buttons and my form_tag (but then referencing them with the html5 form tag) is changing the behaviour somehow? Thanks in advance, I've been pulling out my hair on this one.




Aucun commentaire:

Enregistrer un commentaire