我已经检查了其他答案,但是没有找到解决我问题的答案,因为从我的验证中删除“attr_accessor”会给我一个错误,指出“password_confirm是一个未定义的方法”。我构建了这个应用程序,最初能够从登录/注册页面创建新用户。现在,当我尝试创建一个新用户时,我得到两个相互矛盾的错误,我无法弄明白。一个是回滚,显示“用户存在”,但用户没有显示在我的数据库中。另一个是我收到错误消息“密码不能为空”和“密码确认不能为空”,尽管两个字段都已填写。
这是我的控制器代码:
def create
user = User.create(name:params[:name], alias:params[:alias], email:params[:email], password:params[:password], password_confirmation:params[:password_confirm])
if !user.errors.messages.empty?
puts '********'
puts user.errors.full_messages
puts '********'
flash[:errors] = user.errors.messages
redirect_to '/users'
else user && user.authenticate(params[:password])
puts '********'
puts user.errors.full_messages
puts '********'
session[:id] = user.id
redirect_to "/ideas"
end
end
这是HTML:
<div class="">
<h3>Register Here:</h3>
<form action="/users/create" method="post">
<input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>">
Name:<input type="text" name='name'><br>
Alias:<input type="text" name='alias'><br>
Email Address:<input type="text" name='email'><br>
Password:<input type="text" name='password'><br>
<p>* Password must be at least 8 characters.</p>
Confirm Password:<input type="text" name="password_confirm"><br>
<input type="submit" value="Register">
</form>
</div>
这是我的模特:
class User < ActiveRecord::Base
has_secure_password
has_many :ideas
has_many :likes
attr_accessor :password_confirm, :password
email_regex = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]+)\z/i
validates :name, presence: {message: ["Name can't be blank"]}
validates :alias, presence: {message: ["Alias can't be blank"]}
validates :password, presence: {message: ["Password can't be blank"]}, :on => :create, length: {minimum: 8}
validates :password_confirm, presence: {message:["Password Confirmation can't be blank"]}, :on => :create
validates :email, presence: {message: ["Email name can't be blank"]}, :format => { :with => email_regex}, :uniqueness => { :case_sensitive => false}, :on => :create
def total_likes
self.likes.sum(:count)
end
def total_posts
self.ideas.sum(:user_id)
end
end
答案 0 :(得分:0)
删除此行,会弄乱ActiveRecord如何为您处理事情。
attr_accessor :password_confirm, :password