2013-04-26 115 views
0

我試圖創建一個應用程序的老師可以選擇每天不在學校的學生。我通過nifty-generators創建了模型。問題是它不會提交給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

您需要在那裏使用嵌套屬性。請通過這個:http://railscasts.com/episodes/196-nested-model-form-part-1並按照。 – 2013-04-26 13:50:45

+0

我可能建議將重命名爲不存在嗎? – 2013-04-26 15:30:14

+0

@SyedAslam我試過neste railscast *修改*沒有運氣。我可以得到正確的參數,但它不會將它傳遞給正確的表格。 – Petter 2013-04-26 19:22:36

回答

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 

應用程序/視圖/天/ _form.html.erb:

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

我最終得到了這個解決方案。我所擁有的唯一可能是simple_form爲關聯生成的輸入和標籤的樣式和包裝。 – Petter 2013-04-30 08:39:24