0

Rails 5.0.0 で新しいアプリを開始し、bcrypt を使用しようとしています。bcrypt リポジトリの指示に従いましたが、取得中に何かが欠けていますActiveModel::ForbiddenAttributesError

は次のuser.rbとおりです。

require 'bcrypt'

class User < ActiveRecord::Base
 include BCrypt

 def password
    @password ||= Password.new(password_hash)
 end

 def password=(new_password)
    @password = Password.create(new_password)
    self.password_hash = @password
 end

 has_many :trips
end

移行の詳細:

class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
        t.string  :first_name,    null: false
        t.string  :last_name,     null: false
        t.string  :email,         null: false
        t.string  :password_hash, null: false

        t.timestamps
    end
  end
end

users_controller.rb :

class UsersController < ApplicationController

  def create
    user = User.new(params[:user])
    user.password = params[:password]
    user.save!
  end

  def new
   @user = User.new
  end

  private

  def user_params
   params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)
  end
end

スタック トレースの先頭は次のとおりです。

Started POST "/users" for ::1 at 2016-09-19 16:44:20 -0700
Processing by UsersController#create as HTML
  Parameters: {"utf8"=>"✓",     "authenticity_token"=>"GWJXon2Y914Y7m2NGPAj8wz+9O6EBO1OnrIcBBRis/ATMkaGMCRh6uE4PAxJOIE7mVrornt5PqOvxBjoOBo9ag==", "user"=>{"first_name"=>"test", "last_name"=>"test2", "email"=>"123@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create User"}
Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)


ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):

app/controllers/users_controller.rb:4:in `create'
  Rendering /Users/.rvm/gems/ruby-2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
4

1 に答える 1

0

エラーが発生する理由は、この行が原因だと思われます

user = User.new(params[:user])

params を渡そうとしてい:userます。そしてあなたのuser_params方法では、

params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)

:user許可されたパラメーターの 1 つではありません。

あなたがしなければならないことは、変化することです

user = User.new(params[:user])

user = User.new(user_params)

関数を呼び出して、user_paramsそれを の引数として渡す必要がありますUser.new

于 2016-09-19T23:54:46.143 に答える