我有一个User
模型,其中有以下验证如何在Rails中执行update_attributes时仅验证特定字段?
validates :username, :presence => true, :uniqueness => true
validates :email, :presence => true, :uniqueness => true
validates :password, :confirmation => true
validates_presence_of :password, :on => :create
validates_presence_of :bnet_username, :on => :update
validates_presence_of :bnet_code, :on => :update
之所以bnet_username
和bnet_code
仅在更新,因为我已经有现有用户,当我加入这些领域,他们还没有在登记表,所以我只需要用户在网站上注册后设置它们。
虽然有一个问题,那就是当没有设置的用户bnet_username
和bnet_code
尝试重置他的密码。在这种情况下,PasswordResetController
将尝试更新其属性,但验证将失败。
if @user.update_attributes(params[:user])
redirect_to root_url, :notice => "Password has been reset! You can now log in."
...
问题是,我需要验证密码,当用户试图重置它,但我不想验证它,当他只是更新他的个人资料。
我也不能跳过验证所有密码重置,因为我需要验证密码本身。
有没有简单的解决方案,如何说哪些验证我需要运行?或者我接近完全错误?
编辑:基本上有一种情况会导致问题。尚未设置其bnet_username
和bnet_code
的现有用户,但他想更改密码。
由于密码更改是更新操作,因此会触发对bnet_username
和bnet_password
的验证。但我需要将它们设置为仅更新,因为我希望用户在编辑其配置文件时设置它们。
当用户注册时,这不是必填字段,但他们在尝试更新配置文件信息时必须设置它。
请展开多一点“但我不希望对其进行验证时,他只是更新他的个人资料。”我在那里得到了一些有趣的逻辑,问题的其他部分是关于是否设置了2个bnet字段,不确定哪个优先。 –
因为我的产品在下面。 –
@MichaelDurrant检查编辑 –