在编写“新”方法时,继续获得“无法找到没有ID的Model_name”

时间:2013-01-14 02:57:22

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

作为背景,我目前有三个模型SchoolCourseSection,它们都是一对多的关系(学校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

2 个答案:

答案 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
希望这会治愈:)