2015-09-21 85 views
0

學生型號:的Rails通過協會創建通過

class Student < ActiveRecord::Base 
    has_many :courses 
end 

課程模式:

class Course < ActiveRecord::Base 
    belongs_to :student 
end 

如何創建通過學生的課程,讓我得到[課程編號:1,student_id數據:1]。我嘗試了以下方法,但它給了我student_id無。

課程控制器:

@course = Student.find(params[:id]) 
@course = @course.new(params[:course]) 

回答

0

有你解決一些小問題,但如果我深知你試圖做什麼,這基本上是創建課程對象與courses_controller一些動作裏面學生相關聯,所有你需要做的就是添加這些行吃了courses_controller行動:

Courses_controller:

class CoursesController < ApplicationController 

    ... 

    def new 
    @student = Student.find(params[:student_id]) 
    @course = Course.new student_id: @student.id 
    end 

    def create 
    @course = Course.new(params[:course]) 
    @course.save 
    end 

    ... 

end 

在你認爲你打電話給new_course_path的情況下,你應該通過:student_id的值,就像這個例子:

new_course_path(student_id: @student.id)