你有一个students_controller
,对应于routes.rb
中的resources :students
行.这会创建使用单词students
的路由,比如students_path
和new_student_path
.使用form_for(@record)
时,url由objects类确定.在这种情况下,@record
是User
,因此当对象是新记录时路径是users_path
,当对象被持久化时路径是user_path(@record)
.由于没有定义users_controller
,因此需要手动设置form_for
的url来修复此错误
form_for @user, url: student_path(@user), html: { method: :put } do |f|
现在,如果您使用名为_form.html.erb
的分部,并且在new和edit操作上都使用该分部,则会出现问题,因为new和edit操作的URL都不同.你必须改变你的观点
# new.html.erb
form_for @user, url: students_path, html: { method: :post } do |f|
render 'form', f: f
# edit.html.erb
form_for @user, url: student_path(@user), html: { method: :put } do |f|
render 'form', f: f
# _form.html.erb
f.text_field :name
f.text_field :title