没有路由匹配{:action =>" change_name",:controller =>"用户",:id => nil}缺少必需的密钥:[:id]

时间:2017-07-28 04:29:42

标签: ruby-on-rails ruby-on-rails-4

我添加了宝石"设计"我收到了这个错误。我无法理解我的代码有什么问题。提前谢谢!

错误:

def user_form
    common_options = { validate: true, html: { class: 'user-form' } }
    form_options = current_user ? [ current_user, { url: change_user_name_path(current_user.id), method: :post, validate: true }.merge(common_options) ] : [ User.new, { validate: true }.merge(common_options) ]
    form_for *form_options do |f|
      yield f
    end
  end

路线

Rails.application.routes.draw do

  devise_for :users
  devise_for :usernames
  root 'surveys#index'
  resources 'surveys'
  resources 'attempts'
  resources 'users', only: [:create]

  delete 'attempts/:survey_id/:user_id' => 'attempts#delete_user_attempts', as: :delete_user_attempts

  post 'user/:id/change_name' => 'users#change_name', as: :change_user_name

控制器:

class UsersController < ApplicationController
  def create
    session[:user_id] = User.create(user_params).id
    redirect_to :back
  end

  def change_name
    @user = User.find(params[:id])
    @user.update(user_params)
    redirect_to :back
  end

  def user_params
    params.require(:user).permit(:name)
  end
end

有人可以帮忙解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

尝试从模型中删除方法current_user。因为current_user是设备的默认方法,它返回当前登录用户。你是最重要的设计方法。这就是为什么你得到nil ID的错误,因为你的current_user没有任何价值。

它将解决您的问题。