首页 > 解决方案 > NoMethodError(未定义的方法“用户”用于#):

问题描述

当我在我的案例之前添加验证时,它可以正常工作,但是在给我一个错误之后添加验证

在 2018-08-20 07:19:33 +0000 开始为 106.37.100.61 发布“/users” 无法从 106.37.100.61 渲染控制台!允许的网络:127.0.0.1, ::1, 127.0.0.0/127.255.255.255 (0.2ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC 由 UsersController 处理#create as HTML 参数:{"utf8"=>"✓", "authenticity_token"=>"UrrKnE8xR9phK4WEdyrgxgJSItgopSno2ZfyTHC1AIKG3WEs4iE17gDzp5xGzxXSrLG0cqOPP1cht7AvOSQMqQ==", "user"=>{"name"=>"", "email"=>""}, "commit" =>“创建用户”} (0.1ms) 开始事务 (0.1ms) 回滚事务在 25 毫秒内完成 500 内部服务器错误 (ActiveRecord:

NoMethodError(未定义的方法“用户”用于#):

app/controllers/users_controller.rb:31:in 'block in create' app/controllers/users_controller.rb:30:in 'create'

这是我的模型:

class User < ApplicationRecord
  has_many :microposts
  validates :name, presence: true
  validates :email, presence: true
end

我的控制器:

class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]
  before_action :set_user_micropost, 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/new
  def new
    @user = User.new
  end

  # GET /users/1/edit
  def edit
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  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 @user, 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

  def set_user_micropost
      @microposts = @user.microposts
  end

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

标签: ruby-on-railsnomethoderror

解决方案


我知道这会发生什么

validates :name, presence: true 
validates :email, presence: true 

我在 user.rb 文件中更改模型

有用


推荐阅读