Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails 4中的嵌套资源和新表单_Ruby On Rails_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails rails 4中的嵌套资源和新表单

Ruby on rails rails 4中的嵌套资源和新表单,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我有两种课程和类别 resources :categories do resources :courses end 一个类别有许多课程,而一门课程属于一个类别 目前,用户可以单击某个类别并查看该类别中的所有课程,这正是我想要的。但是,当他选择创建一个新课程时,该新课程已分配给一个类别。我想让用户能够创建新课程并从列表中选择类别,但当前路线不允许这样做 new_category_course GET /categories/:category_id/courses/new(.:for

我有两种课程和类别

resources :categories do
  resources :courses
end
一个类别有许多课程,而一门课程属于一个类别

目前,用户可以单击某个类别并查看该类别中的所有课程,这正是我想要的。但是,当他选择创建一个新课程时,该新课程已分配给一个类别。我想让用户能够创建新课程并从列表中选择类别,但当前路线不允许这样做

 new_category_course GET    /categories/:category_id/courses/new(.:format)      courses#new
我不确定我现在应该做什么来实现这一点,任何建议都会有很大帮助

我想让用户能够创建新课程并从列表中选择类别,但当前路线不允许这样做

 new_category_course GET    /categories/:category_id/courses/new(.:format)      courses#new
为了澄清这只是一个路由,它定义了当你点击一个url时,操作控件将在哪个控制器上运行。新课程与动作和表单中的类别关联。如果你看看你的新动作,你会有这样的感觉:

def new
  @category = Category.find(params[:category_id])
  @category.courses.build #this line makes your course associated with your category
  # if you don't want to associated it with the present category then you can simply do:
  # @category = Category.new
  # and then in your form you can have a select and then assign category to that select
end
在您的情况下,可以将rails与以下内容结合使用:

def new
  @category = Category.find(params[:category_id])
  @category.courses.build #this line makes your course associated with your category
  # if you don't want to associated it with the present category then you can simply do:
  # @category = Category.new
  # and then in your form you can have a select and then assign category to that select
end

非常感谢您的回答!:)很抱歉打扰您,因为我的编辑表单和新表单是不同的,在不创建两个不同部分的情况下,设置表单(@course)或表单(@category,@course)的最佳方式(DRY)是什么。是否有一种基于控制器操作创建条件的方法?谢谢again@BadrTazi没有问题:)你能粘贴你的表格吗?将能够更好地帮助你。事实上,我认为你应该用这两种形式问一个新问题,这样可以帮助其他人