【发布时间】:2015-03-31 02:55:47
【问题描述】:
学生.rb
class Student < ActiveRecord::Base
has_many :enrollments
has_many :courses, through: :enrollments
accepts_nested_attributes_for :enrollments
end
注册.rb
class Enrollment < ActiveRecord::Base
belongs_to :student
belongs_to :course
end
课程.rb
class Course < ActiveRecord::Base
has_many :enrollments
has_many :students, through: :enrollments
end
enrollments_controller.rb
class EnrollmentsController < ApplicationController
def new
@current_student = current_user.student
@enrollments = @current_student.enrollments.build
end
def create
current_student = current_user.student
@enrollments = current_student.enrollments.build(enrollment_params)
if @enrollments.save
flash[:success] = "You have successfully enrolled."
redirect_to new_enrollment_path
else
# fail
flash[:danger] = "Please try again."
redirect_to new_enrollment_path
end
end
private
def enrollment_params
params.require(:enrollment).permit(:student_id, :course_id)
end
end
注册/new.html.erb
<%= nested_form_for(@current_student, html: { class: 'form-horizontal' }) do |f| %>
<%= f.fields_for :enrollments do |e| %>
<div class="form-group">
<%= e.label :course_id, for: :course_id, class: 'col-xs-3 control-label' %>
<div class="col-xs-9">
<%= e.collection_select :course_id, Course.all, :id, :name, {prompt: "Select your Course"}, {class: 'form-control'} %>
</div>
</div>
<% end %>
<%= f.link_to_add 'Add Course', :enrollments, class: "col-xs-9 col-xs-offset-3" %>
<div class="form-group">
<div class="col-xs-9 col-xs-offset-3">
<%= f.submit "Enroll Now", class: 'btn btn-primary' %>
</div>
</div>
<% end %>
通过引用:
意图:使用现有课程和学生创建注册。
注册/new.html.erb 的当前实现将在表单上显示所有现有注册,这不是所需的演示视图。
我希望创建一个空白表格来创建注册。 我该怎么做?
【问题讨论】:
标签: ruby-on-rails many-to-many nested-forms has-many-through cocoon-gem