0

在Rails 4中,如何創建表單,通過關聯在has_many中創建連接表中的新行?具體來說,我將什麼傳入我的check_box()輸入?創建一個將新行添加到連接表的表單

例如: 學生報名參加多門課程。這是has_many關聯的has_many。我的連接表是「student_course_assignments」。

型號:

Student 
has_many :student_course_assignments 
has_many :courses, through: :student_course_assignments 
accepts_nested_attributes_for :student_course_assignments 

Course 
has_many :student_course_assignments 
has_many :students, through: :student_course_assignments 

StudentCourseAssignment 
belongs_to :student 
belongs_to :course 

控制器學生

def show 
    @student.student_course_assignments.build 
end 

查看在myapp.com/student/1

# This form lets you add new rows to student_course_assignments, for the given student. 
<%= form_for @student do |f| %> 
    <%= f.fields_for :student_course_assignments do |join_fields| %> 
    <% Courses.all.each do |course| %> 
     <%= join_fields.checkbox(course.id) %> # What should be passed in here?? 
     <span><%= course.name %></span> 
    <% end %> 
    <% end %> 
<% end %> 

如何結構,顯示覆選框每個課程形式的任何建議,讓我檢查應該添加到student_course_assignemnts db的課程將不勝感激。

+0

嘆了口氣,這些問題已被問了很多次...... http://railscasts.com/episodes?utf8=%E2%9C% 93&search = HABTM軌道真的必須讓這更簡單,更清晰! – phoet

+0

這是Rails 3在2011年 - 這個問題的關鍵是找出最有效的方式來構建這使用Rails 4. –

+0

我認爲這方面沒有什麼改變... – phoet

回答

0

ActiveRecord的

你可能會尋找<< ActiveRecord功能:

#config/routes.rb 
resources :students do 
    #could be a member route 
    match :add, via: [:get, :post] 
end 

#app/controller/students_controller.rb 
def add 
    @student = Student.find(params[:student_id]) 
    if request.post? 
     @course = Course.find(params[:course_id]) 
     @student.student_course_assignments << @course 
    end 
end 

#app/views/students/add.html.erb 
<%= form_for @student, method: :post do |f| %> 
    <%= f.text_field :course_id %> 
<% end %> 

此致

爲您的代碼,我應該這樣做:

<%= form_for @student do |f| %> 
    <% Courses.all.each do |course| %> 
     <%= f.checkbox :student_course_assignment_ids, course.id %> 
     <span><%= course.name %></span> 
    <% end %> 
<% end %> 

這將填充我認爲對你的student_course_assignments集合。你不應該使用accepts_nested_attributes_for,如果你沒有創建新的course對象

相關問題