我想我会问一个2部分的问题;如果这应该分成2个问题,我的道歉。simple_form与嵌套属性
首先,我想存储的课程为course
表(课程名称,讲师,START_TIME,END_TIME,等...),这将有course_days
(course_id
和day
与的一天相当于一个ActiveRecord关系周=> 1为星期日,2为星期一等)。我的最终目标是在FullCalendar中将它们显示为一个时间表,这就是为什么我认为将course
和course_days
分隔成两个具有ActiveRecord关系的表格最好。 使用Rails,这是实现这一目标的好方法吗?
如果是这样,其次,我使用简单的形式将以下数据添加到2个表中:course
和course_days
。我想我正在接近。我只是有一些困难,加上course_days
(例如,如果“星期一”,“星期二”和“星期四”检查3个独立的行会被添加到course_days
以下是我目前的工作:
#new.html.erb
<%= simple_form_for @course, html: { autocomplete: 'off' } do |f| %>
<%= f.input :title, label: 'Class Name', placeholder: 'Class Name' %>
<%= f.input :instructor, placeholder: "Instructor Name" %>
<%= f.input :instructor_email, placeholder: 'Instructor Email' %>
<%= f.input :building, placeholder: 'Building' %>
<%= f.input :room, placeholder: 'Room' %>
<%= f.input :semester do %>
<%= f.select :semester_id, @semesters.map { |s| [s.name, s.id] } %>
<% end %>
<%= f.simple_fields_for :course_days do |p| %>
<%= p.input :day, :as => :boolean %>
<% end %>
<%= f.button :submit, :class => 'btn btn-primary' %>
#app/models/course.rb
class Course < ActiveRecord::Base
has_many :course_days
accepts_nested_attributes_for :course_days
end
#app/models/course_day.rb
class CourseDay < ActiveRecord::Base
belongs_to :course
end
#app/controllers/courses_controller.rb
def new
@course = Course.new
7.times { @course.course_days.build } #For 7 days of the week??
@semesters = Semester.all()
end
def create
@course = Course.new(course_params)
if @course.save
redirect_to action: 'new'
flash[:notice] = "Course Created."
else
render :new
end
end
def course_params
params.require(:course).permit!
end
任何帮助将不胜感激!
编辑: 我遇到的问题与上面的表格: 1)如何生成7个复选框与分配的属性,以确定它的星期一,星期二等? 2)使用嵌套属性,即使选中了多个复选框,它也只向数据库提交一条记录。
编辑2
所以,从本质上讲,当表单提交,我想数据库表看起来是这样的:
courses: id => 14, name => Bio 101, start_time => 08:00:00, end_time 09:00:00
course_days: id => 11, course_id => 14, day => 1 (For monday)
course_days: id => 12, course_id => 14, day => 3 (For wednesday)
course_days: id => 13, course_id => 14, day => 5 (For friday)
好像是好主意,你关心的是什么?或问题? – juanpastas
嗨@juanpastas,我更新了我的问题。 – Dodinas
你会对这个宝石感兴趣吗:https://github.com/ryanb/nested_form?我认为它可以帮助你实现你想要的。我要做的是...当用户选中“日复选框”时,它会在隐藏的“link_to_add”按钮上单击(使用coffeescript),并按照相应的日期值预先筛选新的嵌套属性之一。你认为这个宝石可以帮你吗?你想让我写一个详细的答案吗? – Kulgar