ruby-on-rails - 未定义的方法 password_changed?错误

标签 ruby-on-rails validation nomethoderror password-confirmation

我正在尝试设置我的程序,以便仅在更改密码时验证密码(因此用户可以编辑其他信息而无需输入密码)。

我目前收到一个错误提示

NoMethodError in UsersController#create, undefined method `password_changed?' for #<User:0x00000100d1d7a0>

当我尝试登录时。

这是我在 user.rb 中的验证码:
    validates :name,  :presence => true,
 :length   => { :maximum => 50 }
validates :email, :presence   => true,
:format     => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
validates :password, :presence =>true, :confirmation => true, :length => { :within => 6..40 }, :if=>:password_changed?  

这是我在 users_controller.rb 中的创建方法:
def create
    @user = User.new(params[:user])
    if @user.save
        sign_in @user
        flash[:success] = "Welcome to the Sample App!"
        redirect_to @user
    else
        @title = "Sign up"
        render 'new'
    end
end

谢谢!

最佳答案

用。。。来代替:

:if => lambda {|user| user.password_changed? }

我会做两种不同的验证:
validates :password, :presence =>true, :confirmation => true, :length => { :within => 6..40 }, :on => :create
validates :password, :confirmation => true, :length => { :within => 6..40 }, :on => :update, :unless => lambda{ |user| user.password.blank? }  

关于ruby-on-rails - 未定义的方法 password_changed?错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7080892/

相关文章:

ruby-on-rails - 空的?使用 default_scope( :order)) 在 ActiveRecord 上失败

ruby-on-rails - Rails 单表继承问题

java - 我们如何在 Spring Boot 中使用任一验证?

javascript - CouchDB 设计文档中的多个 validate_doc_update 函数。有什么好的做法吗?

css - *-tag,*_tag 在 heroku 中部署的 scss 中不起作用

javascript - 是否可以将factory_girl.js 与茶匙一起使用?

使用 react 形式验证 Angular 和 froala 编辑器

methods - 未定义方法 `remember_token=' 'find_by_remember_token' - 第 8 章 Ruby on Rails 教程

ruby - 如何统计选票,处理未定义方法 'push'为nil :NilClass

api - 设计 sign_in 方法在 RSpec 测试中抛出 NoMethodError