无法通过嵌套表单提交Checkbox

时间:2013-04-26 13:30:42

标签: ruby-on-rails nested-attributes form-for

我试图创建一个应用程序,教师可以选择每天不在学校的学生。我通过漂亮的生成器gem创建了模型。问题是它不会提交到notpresents表。请帮忙。

# == Schema Information
#
# Table name: students
#
#  id         :integer          not null, primary key
#  name       :string(255)
#  group_id   :integer
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Student < ActiveRecord::Base
  attr_accessible :name, :group_id
  belongs_to :days
end


# == Schema Information
#
# Table name: notpresents
#
#  id         :integer          not null, primary key
#  student_id :integer
#  day_id     :integer
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Notpresent < ActiveRecord::Base
  attr_accessible :student_id, :day_id
  belongs_to :days
end


# == Schema Information
#
# Table name: days
#
#  id         :integer          not null, primary key
#  title      :string(255)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Day < ActiveRecord::Base
  attr_accessible :title, :presents 
  has_many :notpresents
  accepts_nested_attributes_for :notpresents
end

并查看_form.html.erb

<%= form_for @day do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </p>

<% for student in Student.find(:all) %>
        <div>
            <%= check_box_tag :notpresents, student.id%>
            <%= student.name %>
        </div>

    <% end %>


  <p><%= f.submit %></p>
<% end %>

1 个答案:

答案 0 :(得分:0)

我从来没有使用漂亮的发电机宝石,但是如果一个学生可以在很多天缺席,而且一天可以让很多学生缺席,那么你不应该有多对多的关系?

class Student < ActiveRecord::Base
  attr_accessible :name
  has_many :days, through: :notpresents
  has_many :notpresent
end

class Days < ActiveRecord::Base
  attr_accessible :date
  has_many :students, through: :notpresents
  has_many :notpresent
end

class :Notpresents < ActiveRecord::Base
  attr_accessible :student_id, :day_id
  belongs_to :students
  belongs_to :days
end

它也可以是 has_and_belongs_to_many 关联,但使用 has_many :through ,您可以使用字符串或文本属性来记录缺席或类似的东西。

我建议在表单中使用simple_form,这样可以轻松实现:

应用程序/控制器/ days_controller.rb:

def edit
  @day = Day.find(params[:id])
end

app / views / days / _form.html.erb:

<%= simple_form_for @day do |f| %>
  <%= f.association :students, as: :check_boxes %>
<% end %>