Rails - HABTM查找或创建嵌套表单

时间:2015-06-09 04:04:06

标签: ruby-on-rails nested-forms has-and-belongs-to-many nested-form-for

我找到了this

我现在的问题是如何创建表单,我正在尝试:

        #students.row
          = f.fields_for :classrooms_students, f.object.classrooms_students do |cs|
            = cs.fields_for :student, cs.object.student do |s|
              / .record is used to fill fields when teacher clicks a .result
              .record
                .col-sm-6 style=("margin-top: 10px;")
                  = s.label :name
                  = s.text_field :name, class: 'form-control autocomplete', data: {autocomplete: :name}
                  .results
                .col-sm-6 style=("margin-top: 10px;")
                  = s.label :email
                  = s.text_field :email, class: 'form-control autocomplete', data: {autocomplete: :email}
                  .results
            .col-sm-12 style=("margin-top: 10px;")
              = cs.link_to_remove 'Remove Student', class: 'btn btn-danger'
          .col-sm-12 style=("margin-top: 10px;")
            = f.link_to_add 'Add Student', :classrooms_students, "data-target" => '#students', class: 'btn btn-primary'

问题是在服务器中我得到了:

{"classroom"=>
  {"name"=>"qwerqqeq",
   "description"=>"",
   "note"=>"",
   "classrooms_students_attributes"=>
    {"0"=>
      {"student_attributes"=>{"name"=>"vsrjh", "email"=>"fgh@fgh.com", "id"=>"33"},
       "_destroy"=>"false",
       "id"=>""},
     "1"=>
      {"student_attributes"=>{"name"=>"cvbcbc", "email"=>"yui@yui.com", "id"=>"32"},
       "_destroy"=>"false",
       "id"=>""}}}}

加入哈希值id'',Rails如何查找记录?

所以我得到了:

undefined method `to_sym' for nil:NilClass.

我应该在联接表中添加id列吗?

1 个答案:

答案 0 :(得分:0)

我添加了index

    add_column :classrooms_students, :id, :primary_key