0

student.rb多到多用的has_many:通過關聯嵌套形式

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

通過referering到:

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

意向:與現有課程和學生創建擴招

當前的enrollment/new.html.erb實現將顯示錶單上不是所需演示視圖的所有現有註冊。

我希望創建一個空白表單來創建註冊。 我該怎麼做?

回答

0

只需添加一行,「!e.object.persisted?」它解決了這個問題。

註冊/ 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 %> 
+0

這似乎有點不可思議:只顯示(或允許編輯)入學率,如果他們是新的?那麼爲什麼要使用繭,而不僅僅是創建一個新的註冊,並且給用戶(已知),作爲一個隱藏的領域。另外:現在我明白你的問題了,以前我完全不清楚。一個替代測試是'e.object.new_record?',它可能會或可能不會更清楚(這對我來說,但可能是個人的:)) – nathanvda 2015-04-01 22:39:55

+0

@nathanvda,因爲在一個單一的頁面中,我想讓用戶創建多個註冊。通過使用cocoon/nested表單,我可以從f.link_to_add腳本函數創建動態多註冊表創建。 感謝您的建議,我會嘗試另一種方式「e.object.new_record?」 – 2015-04-26 09:35:39