1

私はしばらくの間、この質問の繰り返しを求めてきましたが、SOコミュニティからの多くの助けを借りて、ほとんど機能しています。それではまず、よろしくお願いします!

私は新しいフォームを作成し、宝石student_groupを使用しています:Cocoon

<%= form_for @student_group do |f| %>

  <p>
    The name of this group is 
    <span class="field form_field"><%= f.text_field :name %></span>
    and it is a/an 
    <span class="field dropdown"><%= f.select :type_of_group, [["select a group type", ""], "young learners class (0-6)", "primary class (7-12)", "secondary class (13-17)", "adult class (18+)", "children's sport team", "adult's sport team"]  %></span>       
  </p>

  <p>
    There are 
    <span id="nos" class="field dropdown"><%= f.select :number_of_students, (0..60) %></span>
    students in this group.   
  </p>


  <table id="students_form_table">
    <tbody>
      <!-- https://stackoverflow.com/questions/11445831/how-to-submit-multiple-new-items-via-rails-3-2-mass-assignment -->
      <%= f.fields_for :students, @student, child_index: @student do |builder| %>
        <%= render "student_fields", :f => builder %>
      <% end %>
    </tbody>    
  </table>

  <p>
    <%= f.submit "Submit", :class => 'big_button round unselectable'%>
  </p>

<% end %>

および 'student_fields' パーシャル:

<tr class="nested-fields">
  <td id="student_name" class="field form_field"><%= f.text_field :name, placeholder: "Student name" %></td>
  <td id="student_gender" class="field dropdown"><%= f.select :gender, [["select a gender", ""],'Female', 'Male', 'Transgender'] %></td>
  <td id="remove_link"><%= link_to_remove_association "remove student", f %></td>
</tr>

質問の核心:

次の .js ファイルを使用して、正しい数の学生フィールドをフォームに動的に追加します。

var row_i = 0;

function emptyRow() {
row_i++;
this.obj = $("<tr></tr>");
this.obj.append('<td id="student_name" class="field form_field"><input id="student_group_students_attributes___Student:0x00000103c4ead8__name" name="student_group[students_attributes][#&lt;Student:0x00000103c4ead8&gt;][name]" type="text" /></td>');
this.obj.append('<td id="student_gender" class="field dropdown"><select id="student_group_students_attributes___Student:0x00000103c4ead8__gender" name="student_group[students_attributes][#&lt;Student:0x00000103c4ead8&gt;][gender]"><option value="">select a gender</option><option value="Female">Female</option><option value="Male">Male</option><option value="Transgender">Transgender</option></select></td>');
this.obj.append(' <td id="remove_link"><input id="student_group_students_attributes___Student:0x00000103c4ead8___destroy" name="student_group[students_attributes][#&lt;Student:0x00000103c4ead8&gt;][_destroy]" type="hidden" /><a href="#" class="remove_fields dynamic">remove student</a></td>')
}

function refresh(new_count) {
  //how many students we have got?
  console.log("New count= " + new_count);
  if (new_count > 0) {
    $('#students_form_table').show();
  } 
  else {
    $('#students_form_table').hide();
  }

 var old_count = parseInt($('tbody').children().length);
   console.log("Old count= " + old_count);
   //calculates difference between rows needed/rows current
 var rows_difference = parseInt(new_count) - old_count;
   console.log("Rows diff= " + rows_difference);
   //if we have rows to add
 if (rows_difference > 0) {
   for (var i = 0; i < rows_difference; i++)
   $('tbody').append((new emptyRow()).obj);
 } else if (rows_difference < 0) //we need to remove rows ..
 {
   var index_start = old_count + rows_difference + 1;
   console.log("Index start= " + index_start);
   $('tr:gt(' + index_start + ')').remove();
   row_i += rows_difference;
 }
}

$(document).ready(function () {
  //hide table by default
  $('#students_form_table').hide();

  $('#nos').change(function () {
    var opt=$('#nos option:selected');
    refresh(opt.text());
  })

});

したがって、このフォームはほとんど機能します-すべてが正しくフォーマットされ、「x」数の学生を選択すると、「x」数の学生フォームが構築されます-ただし、これにより-

function emptyRow() {
  row_i++;
  this.obj = $("<tr></tr>");
  this.obj.append('<td id="student_name" class="field form_field"><input id="student_group_students_attributes___Student:0x00000103c4ead8__name" name="student_group[students_attributes][#&lt;Student:0x00000103c4ead8&gt;][name]" type="text" /></td>');
  this.obj.append('<td id="student_gender" class="field dropdown"><select id="student_group_students_attributes___Student:0x00000103c4ead8__gender" name="student_group[students_attributes][#&lt;Student:0x00000103c4ead8&gt;][gender]"><option value="">select a gender</option><option value="Female">Female</option><option value="Male">Male</option><option value="Transgender">Transgender</option></select></td>');
  this.obj.append(' <td id="remove_link"><input id="student_group_students_attributes___Student:0x00000103c4ead8___destroy" name="student_group[students_attributes][#&lt;Student:0x00000103c4ead8&gt;][_destroy]" type="hidden" /><a href="#" class="remove_fields dynamic">remove student</a></td>')
}

...フィールドが正しくレンダリングされていません。つまり、新しい学生フィールドの個別のインスタンスを作成していないということです。問題は、レールによって生成された html の id/name 部分のハッシュであることは理解していますが、これが機能するようにそれを置き換える方法がわかりません。私が最も近づいたのは、このサイトのコーヒースクリプトを適応させようとしたことですが、うまくいきませんでした。

では、jquery を使用してモデルの新しいフォームを動的に生成する方法は?

編集: 実際、最初と最後のフォームが適切に保存されることに気付きました。つまり、8 人の学生を追加すると、student1 と student8 はデータベースに入力されますが、他のフォームは入力されません。これは私をもっと混乱させるだけです:/

EDIT 2 :この質問のコンテキストで「serialize」と呼ばれるこのjquery apiを見つけました。必要なものかもしれませんが、適応に問題があると思います。助けて!

4

1 に答える 1

1

とった!

いろいろ試してみましたが、最終的には以下のようになりました。

student_groups_controller.rb #create

def create
  @params = params[:student_group][:students_attributes]
  @student_group = @user.student_groups.build(params[:student_group])
    if @student_group.save
      ###   RE: 'defensive coding' http://stackoverflow.com/questions/14502508/undefined-method-for-nilnilclass-when-pushing-values-to-an-array  
      if @params.present?
        ### http://stackoverflow.com/questions/11355820/rails-3-2-iterate-through-an-array
        @params.each do |student|
          @student_group.students.create(name:"#{student[:name]}", gender: "#{student[:gender]}")
        end
      end    
      # new subject path
      redirect_to class_path(@student_group), flash: { success: "#{@student_group.name} has been added successfully" }   
    else
      @title = "Create a new group"
      flash.now[:error] = "Something's gone wrong.  Please try again!"
      render 'new' 
    end  
end

の関連セクション_groups_form.html.rb

<table id="students_form_table">
  <tbody>
    <!-- http://stackoverflow.com/questions/11445831/how-to-submit-multiple-new-items-via-rails-3-2-mass-assignment -->
    <%= fields_for 'student_group[students_attributes][]', @student, index: nil do |builder| %>
        <%= render "student_fields", :f => builder %>
    <% end %>
    </tbody>    
</table>

最後に、関連する部分student_groups.js:

function emptyRow() {
  row_i++;
  this.obj = $("<tr></tr>");
  this.obj.append('<td id="student_name" class="field form_field"><input id="student_group_students_attributes__name" name="student_group[students_attributes][][name]" placeholder="Student name" size="30" type="text" /></td>');
  this.obj.append('<td id="student_gender" class="field dropdown"><select id="student_group_students_attributes__gender" name="student_group[students_attributes][][gender]"><option value="">select a gender</option><option value="Female">Female</option><option value="Male">Male</option><option value="Transgender">Transgender</option></select></td>');
  this.obj.append('<td id="remove_link"><input id="student_group_students_attributes___destroy" name="student_group[students_attributes][][_destroy]" type="hidden" /><a href="#" class="remove_fields dynamic">remove student</a></td>')
}
于 2013-07-11T11:09:05.597 に答える