作为背景,我目前有三个模型School
,Course
和Section
,它们都是一对多的关系(学校has_many
课程和课程has_many
部分,并在模型中也建立了相应的belongs_to
关系。我还有以下资源(稍后要设置的排除项):
resources :schools do
resources :courses
end
resources :sections #not part of the nest
尽管sections
可以作为嵌套资源的一部分,但我保留了它,因为Rails guide强烈建议只嵌套一层深层。
所以,我的麻烦在于创建一个新的部分(在SectionsController
中),并通过course_id
def new
@course = Course.find(params[:id]) #this line results in an error
@section = @course.sections.new
end
第一行总是引发“无法找到没有ID的课程”错误,尽管我尝试了各种不同的使用组合:id,:course_id等,但我无法通过该错误。{{1}是一个嵌套资源,还有其他我缺少的东西吗?谢谢你的帮助!
运行Course
时,输出结果如下:
rake routes
答案 0 :(得分:1)
由于您的课程与学校嵌套,请尝试此
你的模型应该
class School < ActiveRecord::base
has_many :courses
end
class Course < ActiveRecord::base
belongs_to :school
end
def new
school = School.find(params[:school_id])
@course = school.courses.new
#your code
end
您可以通过运行
了解此路由rake routes
HTH
答案 1 :(得分:1)
您需要在新的部分请求中包含这些参数
{:School_id=> some_id, :course_id=>some_id}
这样你就可以通过课程
获得部分绑定在区段控制器中
def new
@school = School.find(params[:school_id])
@course = @school.courses.where(:id=>params[:course_id]).first
@section = @course.sections.new
end
希望这会治愈:)