form_for undefined method `user_path'

前端 未结 3 1831
梦谈多话
梦谈多话 2020-12-07 16:21

I\'m getting an error :

undefined method `user_path\' for #<#:0x007fd1f2241af0>

when I\'m trying to edi

3条回答
  •  暖寄归人
    2020-12-07 16:42

    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|
    

    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
    

提交回复
热议问题