jeudi 10 novembre 2016

Rails: editing a form with checkboxes

I have a form with a list of checkbox entries. When I edit an entry the form comes up with all the boxes checked, regardless of what was checked when the form was submitted.

How do I make it 'remember' the checks?

This is my controller's update action:

def update
  @student = Student.find(params[:id])
  if @student.update_attributes!(params[:student])
    flash[:success] = "Student updated"
    redirect_to @student
  else
    render 'edit'
  end
end

This is my view:

<% c = [ 'Characteristic_The_First', 'Characteristic_The_Second',
     'Characteristic_The_Third', 'Characteristic_The_Fourth',
     'Characteristic_The_Fifth', 'Characteristic_The_Sixth' ] %>

<% i = 0 %>

<div> Characteristics </div>
<%= f.fields_for :characteristics, :wrapper => false do |char| %>
  <div>
    <%= char.check_box :name, {class: "checkme"}, c[i], c[i] %>
    <%= char.label :name, c[i], {class: "medium_font"} %>
    <%= char.text_area :notes, {id: c[i], hidden: "true"} %>
    <% i+=1 %>
  </div>
<% end %>

Checkboxes reveal hidden textboxes through this jquery (though this probably isn't relevant to the question):

$( document ).ready(function() {
  $('.checkme').click(function(){
    if($("#" + $(this).val()).attr('hidden')){
      $("#" + $(this).val()).attr('hidden', false);
    }else{
      $("#" + $(this).val()).attr('hidden', true);
    }
  });
});




Aucun commentaire:

Enregistrer un commentaire