Railsvalidation可防止保存

我有这样的用户模型:

class User  true, :confirmation => true, :length => { :within => 6..40 } . . . end 

在User模型中,我有一个我想要从OrdersController保存的billing_id列,如下所示:

 class OrdersController  'billing id saved') else redirect_to(root_url), :notice => @thisuser.errors) end end end end 

由于validates :password用户模型中的validates :password@thisuser.save不保存。 但是,一旦我注释掉validation, @thisuser.save返回true。 这对我来说是一个陌生的领域,因为我认为这个validation仅在创建新用户时有效。 有人可以告诉我是否validates :password每次我尝试保存在用户模型时, validates :password应该启动? 谢谢

您需要指定何时运行validation,否则它们将在每次save调用时运行。 但这很容易限制:

 validates :password, :presence => true, :confirmation => true, :length => { :within => 6..40 }, :on => :create 

另一种方法是有条件地进行此validation触发:

 validates :password, :presence => true, :confirmation => true, :length => { :within => 6..40 }, :if => :password_required? 

您可以定义一个方法,指示在认为此模型有效之前是否需要密码:

 class User < ActiveRecord::Base def password_required? # Validation required if this is a new record or the password is being # updated. self.new_record? or self.password? end end 

这可能是因为您确认密码已经确认( :confirmation => true ),但password_confirmation不存在。

你可以将其分解为:

 validates_presence_of :password, :length => { :within => 6..40 } validates_presence_of :password_confirmation, :if => :password_changed? 

我喜欢这种方法,因为如果用户更改了密码,则需要用户输入相同的password_confirmation。