使用cocoon创建嵌套的子模型

时间:2013-07-04 13:07:47

标签: ruby-on-rails-3 cocoon-gem

编辑 - 已修复:问题是params哈希,在查看了很多关于SO的问题后,我想出了以下解决方案,(到目前为止)效果很好:

student_groups#new动作现在看起来像这样 - 也许有更好的解析参数的方法,但是......这个有效!

  def create
@student_group = @user.student_groups.build(params[:student_group])
###   https://stackoverflow.com/questions/2610263/how-to-access-nested-params
@params = params[:student_group][:students_attributes]
if @student_group.save
  ###    https://stackoverflow.com/questions/14502508/undefined-method-for-nilnilclass-when-pushing-values-to-an-array  
  if @params.present?
    @params.values.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  

student_group.rb:我必须将:_destroy标记为attr_accessor

class StudentGroup < ActiveRecord::Base
  ###    https://github.com/ryanb/nested_form/issues/222
  attr_accessor :_destroy
  attr_accessible :name, :number_of_students, :type_of_group, :students_attributes

  belongs_to :user
  has_one    :age, dependent: :destroy
  has_many   :students, dependent: :destroy

  accepts_nested_attributes_for :students, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true

  ...

end

_groups_form.html.erb:根据this

添加了child_index
<%= 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> 
  <!--  <span id="nos" class="field dropdown"><%#= f.select :number_of_students, (0..60) %></span>  -->
  </p>


  <table id="nos_header">
    <thead>
      <tr>
        <th>Student name:</th>
        <th>Gender:</th>
      </tr>
    </thead>
  <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 %>
        <tr>
          <td class="links"><%= link_to_add_association 'add student', f, :students %></td>
        </tr>
  </tbody>
  </table>

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

<% end %>

结束编辑

我正在使用rails 3.2.13cocoon在我的student_group模型中创建一个嵌套表单。格式化仍然有点棘手,我想实现coffeescript自动更新正确数量的学生,但这些是我以后可以弄清楚的事情。目前,主要问题是,当表单显示并且可以无错误地填写/提交时,不会创建新的子模型。

这是_form部分

<%= 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>
    <!--  <span id="nos" class="field dropdown"><%#= f.select :number_of_students, (0..60) %></span>  --> 
  </p>


  <table id="nos_header">
  <thead>
    <tr>
      <th>Student name:</th>
      <th>Gender:</th>
    </tr>
  </thead>
  <tbody>    
    <%= f.fields_for :students do |builder| %>
      <%= render "student_fields", :f => builder %>
    <% end %>
    <td class="links"><%= link_to_add_association 'add student', f, :students %></td>
  </tbody>
</table>

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

<% end %>

_student_fields部分:

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

当我在浏览器中创建一个新组时,不会创建新学生,我可以在服务器中看到这一点:

Started POST "/student_groups" for 127.0.0.1 at 2013-07-04 14:58:51 +0200
Processing by StudentGroupsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"u/DbVbgMKoT6kWPBKsD0sVNBLVRpFY87E5nZQWK+K9o=", "student_group"=>{"name"=>"test", "type_of_group"=>"young learners class (0-6)", "students_attributes"=>{"1372943007652"=>{"name"=>"Johnny Test", "gender"=>"Male", "_destroy"=>""}, "1372943009403"=>{"name"=>"Quizzy", "gender"=>"Transgender", "_destroy"=>""}}}, "commit"=>"Submit"}
User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 56 LIMIT 1
(0.1ms)  begin transaction
SQL (0.6ms)  INSERT INTO "student_groups" ("created_at", "name", "number_of_students", "type_of_group", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?)  [["created_at", Thu, 04 Jul 2013 12:58:51 UTC +00:00], ["name", "Test"], ["number_of_students", nil], ["type_of_group", "adult class (18+)"], ["updated_at", Thu, 04 Jul 2013 12:58:51 UTC +00:00], ["user_id", 56]]
(2.4ms)  commit transaction
Redirected to http://localhost:3000/class/407
Completed 302 Found in 8ms (ActiveRecord: 3.3ms)

这个哈希似乎是个问题 -

"students_attributes"=>{"1372943007652"=>{"name"=>"Johnny Test", "gender"=>"Male", "_destroy"=>""}, "1372943009403"=>{"name"=>"Quizzy", "gender"=>"Transgender", "_destroy"=>""}}

这些学生属性应该去哪里?我应该如何处理这些属性以便他们创建一个新学生?谢谢!

1 个答案:

答案 0 :(得分:0)

有关解决方案的详细信息,请参阅原始帖子顶部的编辑。回答所以这个问题已经结束了。