Rails验证可防止保存

rai*_*ner 3 validation ruby-on-rails

我有这样的用户模型:

class User < ActiveRecord::Base
    validates :password, :presence => true,
                         :confirmation => true,
                         :length => { :within => 6..40 }
    .
    .
    .
end
Run Code Online (Sandbox Code Playgroud)

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

class OrdersController < ApplicationController
    .
    .
    .
    def create
        @order = Order.new(params[:order])
        if @order.save
            if @order.purchase
                response = GATEWAY.store(credit_card, options)
                result = response.params['billingid']
                @thisuser = User.find(current_user)
                @thisuser.billing_id  = result
                if @thisuser.save
                        redirect_to(root_url), :notice => 'billing id saved')
                    else
                        redirect_to(root_url), :notice => @thisuser.errors)
                    end
            end
        end
    end
Run Code Online (Sandbox Code Playgroud)

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

tad*_*man 12

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

validates :password,
  :presence => true,
  :confirmation => true,
  :length => { :within => 6..40 },
  :on => :create
Run Code Online (Sandbox Code Playgroud)

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

validates :password,
  :presence => true,
  :confirmation => true,
  :length => { :within => 6..40 },
  :if => :password_required?
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)