作为背景,我目前有三个模型,School
, Course
和Section
,它们都是一对多的关系(School has_many
课程和Course has_many
部分,在模型中也建立了相应的belongs_to
关系)。我还有以下资源(稍后设置排除):
resources :schools do
resources :courses
end
resources :sections #not part of the nest
虽然sections
可以作为嵌套资源的一部分,但我保留了它,因为Rails指南强烈建议只嵌套一层。
所以,我的麻烦是,当它涉及到创建一个新的部分(在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等的各种不同组合,但我无法通过。因为Course
是一个嵌套的资源,还有别的东西,我错过了吗?谢谢你的帮助!
当运行rake routes
时,输出如下:
sections GET /sections(.:format) sections#index
POST /sections(.:format) sections#create
new_section GET /sections/new(.:format) sections#new
edit_section GET /sections/:id/edit(.:format) sections#edit
section GET /sections/:id(.:format) sections#show
PUT /sections/:id(.:format) sections#update
DELETE /sections/:id(.:format) sections#destroy
school_courses GET /schools/:school_id/courses(.:format) courses#index
POST /schools/:school_id/courses(.:format) courses#create
new_school_course GET /schools/:school_id/courses/new(.:format) courses#new
edit_school_course GET /schools/:school_id/courses/:id/edit(.:format) courses#edit
school_course GET /schools/:school_id/courses/:id(.:format) courses#show
PUT /schools/:school_id/courses/:id(.:format) courses#update
DELETE /schools/:school_id/courses/:id(.:format) courses#destroy
schools GET /schools(.:format) schools#index
POST /schools(.:format) schools#create
new_school GET /schools/new(.:format) schools#new
edit_school GET /schools/:id/edit(.:format) schools#edit
school GET /schools/:id(.:format) schools#show
PUT /schools/:id(.:format) schools#update
DELETE /schools/:id(.:format) schools#destroy
root /
由于您的课程与学校嵌套,请尝试使用
你的模型应该有
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
您需要在新的section请求中包含这些参数
{:School_id=> some_id, :course_id=>some_id}
这样你就可以用course
获得section绑定In section controller
def new
@school = School.find(params[:school_id])
@course = @school.courses.where(:id=>params[:course_id]).first
@section = @course.sections.new
end