form_for 中的未定义方法“user_path”

Undefined method `user_path' in form_for

我有用户模型和角色模型。

class User < ActiveRecord::Base

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_one :role

  def has_role?(role_name)
    self.role == Role.where(name: role_name).first
  end 

  def add_role(role_name)
    role = Role.where(name: role_name).first
    self.role = role unless  role.blank?
  end

end

class Role < ActiveRecord::Base
    belongs_to :user
end

目前,我的应用程序有 2 个用户角色;管理员和会员。

我现在想做的是,让管理员能够使用 select 标签更改成员的角色(从管理员到成员或从成员到管理员)。

我的 views/users/_form.html.erb

里面有这个
<div class="col-md-4">

<%= form_for(@user) do |f| %>
  <% if @user.errors.any? %>
    <div id="error_explanation">
      <p><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</p>

      <ul>
      <% @user.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="form-group">
    <%= f.label :email %><br>
    <%= f.text_field :email, class: "form-control" %>

    <%= f.label :role %>
    <%= f.select :role_id, options_for_select(Role.all.map{|c| [c.name, c.id]}, f.object.role_id)%>   
  </div>
  <%= f.submit 'Save user', :class => 'btn btn-primary' %>
  <%= link_to 'Back', users_path, class: "btn btn-primary" %>
  <% end %>

</div>

这是我的用户控制器:

class UsersController < ApplicationController
    before_action :authenticate_user!

    before_action :set_user, only: [:show, :edit, :update, :destroy]

  # GET /users
  # GET /users.json
  def index
    @users = User.all
  end

  # GET /users/1
  # GET /users/1.json
  def show
  end

  # GET /users/1/edit
  def edit
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to users_path, notice: 'user was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'user was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:email, :encrypted_password)
    end
end

这是我的 routes.rb:

Rails.application.routes.draw do

  devise_for :users
  root "orders#index"

  resources :orders
  resources :drinks
  resources :foods

  # link to change foods/drinks status from 0 (processing) to 1 (done)
  get '/orders/:id/update_foods_status',  to: 'orders#update_foods_status',   as: :update_foods_status
  get '/orders/:id/update_drinks_status', to: 'orders#update_drinks_status',  as: :update_drinks_status

  # kitchen foods orders
  get 'kitchen_foods',  to: 'kitchen_foods#index'

  # kitchen drinks orders
  get 'kitchen_drinks', to: 'kitchen_drinks#index'

  # list of all users
  get 'users',          to: 'users#index',  as: :all_users

  # single user
  get 'users/:id',      to: 'users#show',    as: :single_user

  # edit user
  get 'users/:id/edit', to: 'users#edit',    as: :edit_user  
end

更新:这是我在 运行 rake routes

之后得到的
Prefix Verb   URI Pattern                                Controller#Action
        new_user_session GET    /users/sign_in(.:format)                   devise/sessions#new
            user_session POST   /users/sign_in(.:format)                   devise/sessions#create
    destroy_user_session DELETE /users/sign_out(.:format)                  devise/sessions#destroy
           user_password POST   /users/password(.:format)                  devise/passwords#create
       new_user_password GET    /users/password/new(.:format)              devise/passwords#new
      edit_user_password GET    /users/password/edit(.:format)             devise/passwords#edit
                         PATCH  /users/password(.:format)                  devise/passwords#update
                         PUT    /users/password(.:format)                  devise/passwords#update
cancel_user_registration GET    /users/cancel(.:format)                    devise/registrations#cancel
       user_registration POST   /users(.:format)                           devise/registrations#create
   new_user_registration GET    /users/sign_up(.:format)                   devise/registrations#new
  edit_user_registration GET    /users/edit(.:format)                      devise/registrations#edit
                         PATCH  /users(.:format)                           devise/registrations#update
                         PUT    /users(.:format)                           devise/registrations#update
                         DELETE /users(.:format)                           devise/registrations#destroy
                    root GET    /                                          orders#index
                  orders GET    /orders(.:format)                          orders#index
                         POST   /orders(.:format)                          orders#create
               new_order GET    /orders/new(.:format)                      orders#new
              edit_order GET    /orders/:id/edit(.:format)                 orders#edit
                   order GET    /orders/:id(.:format)                      orders#show
                         PATCH  /orders/:id(.:format)                      orders#update
                         PUT    /orders/:id(.:format)                      orders#update
                         DELETE /orders/:id(.:format)                      orders#destroy
                  drinks GET    /drinks(.:format)                          drinks#index
                         POST   /drinks(.:format)                          drinks#create
               new_drink GET    /drinks/new(.:format)                      drinks#new
              edit_drink GET    /drinks/:id/edit(.:format)                 drinks#edit
                   drink GET    /drinks/:id(.:format)                      drinks#show
                         PATCH  /drinks/:id(.:format)                      drinks#update
                         PUT    /drinks/:id(.:format)                      drinks#update
                         DELETE /drinks/:id(.:format)                      drinks#destroy
                   foods GET    /foods(.:format)                           foods#index
                         POST   /foods(.:format)                           foods#create
                new_food GET    /foods/new(.:format)                       foods#new
               edit_food GET    /foods/:id/edit(.:format)                  foods#edit
                    food GET    /foods/:id(.:format)                       foods#show
                         PATCH  /foods/:id(.:format)                       foods#update
                         PUT    /foods/:id(.:format)                       foods#update
                         DELETE /foods/:id(.:format)                       foods#destroy
     update_foods_status GET    /orders/:id/update_foods_status(.:format)  orders#update_foods_status
    update_drinks_status GET    /orders/:id/update_drinks_status(.:format) orders#update_drinks_status
           kitchen_foods GET    /kitchen_foods(.:format)                   kitchen_foods#index
          kitchen_drinks GET    /kitchen_drinks(.:format)                  kitchen_drinks#index
               all_users GET    /users(.:format)                           users#index
             single_user GET    /users/:id(.:format)                       users#show
               edit_user GET    /users/:id/edit(.:format)                  users#edit

我的问题:

当我导航到 /users/1/edit 时,出现此错误:

NoMethodError in Users#edit
undefined method `user_path' for #<#<Class:0x007fb702901c88>:0x007fb70098aaf8>

我该如何解决这个问题?

找到了this answer,但是没看明白。希望有更好的解释和回答。

注意:我正在使用 Devise gem

您的路线文件中有:

devise_for :users

这增加了:

        new_user_session GET    /users/sign_in(.:format)                   devise/sessions#new
            user_session POST   /users/sign_in(.:format)                   devise/sessions#create
    destroy_user_session DELETE /users/sign_out(.:format)                  devise/sessions#destroy
           user_password POST   /users/password(.:format)                  devise/passwords#create
       new_user_password GET    /users/password/new(.:format)              devise/passwords#new
      edit_user_password GET    /users/password/edit(.:format)             devise/passwords#edit
                         PATCH  /users/password(.:format)                  devise/passwords#update
                         PUT    /users/password(.:format)                  devise/passwords#update
cancel_user_registration GET    /users/cancel(.:format)                    devise/registrations#cancel
       user_registration POST   /users(.:format)                           devise/registrations#create
   new_user_registration GET    /users/sign_up(.:format)                   devise/registrations#new
  edit_user_registration GET    /users/edit(.:format)                      devise/registrations#edit
                         PATCH  /users(.:format)                           devise/registrations#update
                         PUT    /users(.:format)                           devise/registrations#update
                         DELETE /users(.:format)                           devise/registrations#destroy

现在您要做的是允许管理员编辑用户。为此,您定义了:

  # list of all users
  get 'users',          to: 'users#index',  as: :all_users

  # single user
  get 'users/:id',      to: 'users#show',    as: :single_user

  # edit user
  get 'users/:id/edit', to: 'users#edit',    as: :edit_user

生成:

       all_users GET    /users(.:format)                           users#index
     single_user GET    /users/:id(.:format)                       users#show
       edit_user GET    /users/:id/edit(.:format)                  users#edit

现在在您正在编写的表单中 <%= form_for(@user) do |f| %> 默认情况下正在搜索 user_path。因此,您定义的不是不同的路线,而是添加:

resources :users

这将生成您需要的所有必要路由并将表单映射到正确的路径。这将节省大量开销,例如仅使用此 <%= form_for(@user) do |f| %> 将在用户是新对象时将您带到创建操作,如果用户是持久对象,它将带您到更新操作。

或者如果您需要使用您的路线,那么您需要这样做:

<%= form_for(@user, url: edit_user_path, method: :get) do |f| %>

但是在表单提交中使用GET 方法总是一个坏主意。这些链接可能对您有所帮助:

When should I use GET or POST method? What's the difference between them?

When do you use POST and when do you use GET?

更新:

由于您需要从多个角色中为用户分配一个角色,因此最好使用这样的 select 框:

f.collection_select(:role_id, Role.all, :id, :name)

假设 user table 具有属性 role_id 并且 role table 具有属性 name。因此,这将允许您为用户分配角色。您正在打印的是 user.role,它将始终打印关联而不是角色名称。

希望这对您有所帮助。

如果您想 link 到编辑页面,请尝试使用 edit_user_path 而不是 user_path。如果您查看 routes.rb 文件,则没有 user_path.

的路由