我正在尝试向我的用户模型添加验证:
class User < ActiveRecord::Base
validates :first_name, :last_name, :email, :password, presence: true
当验证到位时,它会阻止我“删除”......我通过将is_delete
字段设置为1
. 我怀疑这与我实际上没有存储:password
. 相反,我有对输入的密码加盐和散列的回调,并将它们保存到相应的字段中(散列密码和加盐)。
如果我尝试验证这些,它会阻止创建:
class User < ActiveRecord::Base
validates :first_name, :last_name, :email, :hashed_pasword, :sal, presence: true
这是有道理的,因为提交表单时它们不存在。
我该如何解决这个问题?
更新 在控制器中...
def delete_user
user = User.find( params[:id] )
# if !user
# flash[:error] = "Problem deleting user"
# redirect_to controller:'admin', action:'index'
# end
if ( user.update( is_deleted: 1) )
flash[:notice] = "User successfully deleted"
else
flash[:error] = "Problem deleting user"
end
redirect_to controller:'admin', action:'index'
end
更新
我正在尝试使用下面悉尼建议的语法,这是我得到的错误。当我使用这个validates :password, length: { in: 6..20}, on: [:update, :create]
,然后“删除”一个用户时,我得到这个:
/Users/ME/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:393: syntax error, unexpected '[', expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END ...ue && (validation_context == :[:update, :create]) ... ^ /Users/ESL/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:402: syntax error, unexpected keyword_end, expecting ')' /Users/ESL/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:429: syntax error, unexpected keyword_end, expecting ')' /Users/ESL/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:430: syntax error, unexpected end-of-input, expecting ')'