在编写“新”方法时,继续获得“无法找到没有ID的Model_name”
作为背景,我目前有三个模型, School
, Course
和Section
,他们都是一对多的关系(学校has_many
课程,课程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
您需要在新的部分请求中包含这些参数
{: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
希望这会治愈:)
- Ruby on Rails的所有“约定”是什么?
- 使用Twitter Bootstrap的Rails:仍在提供旧资产
- ActiveAdmin中的Formtastic提示问题(不需要的对象ID输出)
- 执行Bundle安装时MySql出错
- rails 5 form_tag具有原始DB值,并且在表单中进行新选择后,必须更新两个记录
- 如何搜索记录然后将其删除
- Rails:找出哪个文件导致Sass :: SyntaxErrorexception?
- Rails 4:如何通过AJAX更新基于另一个collection_select的collection_select?
- Rails 3初始化程序只在`rails server`上运行而不是`rails generate`等