form_for 未定义的方法`user_path' [英] form_for undefined method `user_path'
问题描述
我收到一个错误:
undefined method `user_path' for #<#<Class:0x007fd1f223ead0>:0x007fd1f2241af0>
当我尝试编辑学生时.我不太了解user_path"方法警报,因为我从未在视图中写过这个.(学生不是模特)而且我没有使用 rails g scaffold 生成它.
when I'm trying to edit a student. I don't really understand the "user_path" method alert since I never write this in the view. (Student is not model) and I didn't use rails g scaffold to generate it.
谢谢
在我的 StudentsController 中:
In my StudentsController :
def edit
@student = User.find(params[:id])
end
在视图 (edit.html.erb) 中:
In the view (edit.html.erb) :
<%= form_for(@student) do |f| %> ...
在 routes.rb 中:
In routes.rb :
resources :students
推荐答案
你有一个 students_controller
对应于你的 routes 中的
.这将创建使用单词 resources :students
行.rbstudents
的路由,例如 students_path
和 new_student_path
.使用 form_for(@record)
时,url 由对象类确定.在这种情况下,@record
是一个 User
所以当对象是一个新记录和 user_path(@record)
当对象被持久化时.由于您没有定义users_controller
,您需要手动设置form_for
的url 来修复此错误
you have a students_controller
which corresponds to the resources :students
line in your routes.rb
. This creates routes that uses the word students
like students_path
and new_student_path
. When using form_for(@record)
, the url is determined from the objects class. In this case, @record
is a User
so the path is users_path
when the object is a new record and user_path(@record)
when the object is persisted. since you don't have a users_controller
defined, you need to manually set the url of the form_for
to fix this error
form_for @user, url: student_path(@user), html: { method: :put } do |f|
现在,如果您使用名为 _form.html.erb
的部分并在 new 和 edit 操作中使用它,您将遇到问题,因为两个 new 的 url和编辑操作是不同的.你必须把你的观点改成这样
now, if you're using a partial called _form.html.erb
and uses this on both the new and edit actions, you're going to have a problem since the urls for both new and edit actions are different. you have to change your views to something like this
# 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
这篇关于form_for 未定义的方法`user_path'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!