2016-09-19 85 views
0

我在Rails 5.0.0上启动一个新应用程序,并试图使用bcrypt。我已经按照在bcrypt回购的方向,但缺少的东西当我越来越ActiveModel::ForbiddenAttributesError在Rails上启用Bcrypt 5

这里是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"=>"[email protected]", "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 

回答

0

在我看来,你所得到的错误的原因是因为该行

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

您正在尝试通过的params :user。而在你user_params方法,

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

:user是不是允许PARAMS之一。

你需要做的是改变

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

user = User.new(user_params) 

你需要调用user_params功能和传递为User.new参数。

+0

是的,这就是为什么不应该从文档复制/粘贴...谢谢! – Yaron