我正在使用使用Angular和Rails的应用。我正在尝试创建新用户,但不断收到此错误:
BCrypt::Errors::InvalidHash (invalid hash):
app/models/user.rb:14:in `new'
app/models/user.rb:14:in `password'
app/controllers/users_controller.rb:8:in `create'
似乎Angular正在创建一个密码,但它没有传递给Rails。
Parameters: {"first_name"=>"John", "last_name"=>"Smith", "email"=>"john.smith@gmail.com", "username"=>"johnsmith", "password"=>"[FILTERED]", "user"=>{"first_name"=>"John", "last_name"=>"Smith", "username"=>"johnsmith", "email"=>"john.smith@gmail.com"}}
以下是我的前端代码:
app.js
$scope.signUp = function() {
var newUser = {first_name: $scope.firstName, last_name: $scope.lastName, email: $scope.email, username: $scope.username, password: $scope.password}
$http.post('http://localhost:3000/users', newUser)
.success(function(data) {
console.log(data);
if (data.errors) {
console.log(data.errors);
}
else {
$location.path("/sign_in");
}
})
};
signup.html
<div class="form-group has-success signup-box">
<form name="signupForm" novalidate>
<input type="text" ng-required="true" class="form-control" placeholder="First Name" ng-model="firstName"/>
<input type="text" ng-required="true" class="form-control" placeholder="Last Name" ng-model="lastName"/>
<input type="text" ng-required="true" class="form-control" placeholder="Email" ng-model="email"/>
<input type="text" ng-required="true" class="form-control" placeholder="Username" ng-model="username"/>
<input type="text" ng-required="true" class="form-control" placeholder="Password" ng-model="password"/>
<input type="submit" ng-disabled="signupForm.$invalid" class="form-control btn btn-success" value="Sign Up" ng-click="signUp()" />
</form>
<a href="/#/sign_in">Sign In</a>
</div>
后端代码:
users_controller.rb
class UsersController < ApplicationController
def create
user = User.new(user_params)
if user.save
render json: "You successfully create account. Please log in with your information."
else
render json: user
end
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :username, :email, :password)
end
end
user.rb
require 'bcrypt'
class User < ActiveRecord::Base
include BCrypt
***
validates :first_name, :last_name, :username, :email, :password, presence: true
***
def password
@password ||= Password.new(password_hash)
end
def password=(new_password)
@password = Password.create(new_password)
self.password_hash = @password
end
end
任何帮助都非常感谢!
答案 0 :(得分:1)
我能够摆脱错误。显然,Rails不喜欢传入数据的格式。在第2行的 app.js 文件中(见问题)我替换了:
{first_name: $scope.firstName, last_name: $scope.lastName, email: $scope.email, username: $scope.username, password: $scope.password}'
与
{user: {first_name: $scope.firstName, last_name: $scope.lastName, email: $scope.email, username: $scope.username, password: $scope.password}}
答案 1 :(得分:0)
您的解决方案完全有效。执行此操作的另一个版本是删除appIdentifier
中user_params
方法中的名称间距:
users_controller
代替,
def user_params
params.permit(:first_name, :last_name, :username, :email, :password)
end