has_many多对多:通过关联嵌套表单

时间:2015-03-31 02:55:47

标签: ruby-on-rails many-to-many nested-forms has-many-through cocoon-gem

student.rb

class Student < ActiveRecord::Base
  has_many :enrollments
  has_many :courses, through: :enrollments

  accepts_nested_attributes_for :enrollments
end

enrollment.rb

class Enrollment < ActiveRecord::Base
  belongs_to :student
  belongs_to :course
end

course.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 %>

参考:

many-to-many: has_many :through association form with data assigned to linking model create form view

意图:使用现有课程和学生创建注册

enrollment / new.html.erb的当前实现将显示表单上不是所需演示文稿视图的所有现有注册。

我希望创建一个用于创建注册的空白表单。 我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

只需添加一行,&#34;!e.object.persisted?&#34;它解决了这个问题。

登记/ new.html.erb

<%= f.fields_for :enrollments do |e| %>

    <!--  -->
    <% if !e.object.persisted? %>
      <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 %>
<% end %>