ruby-on-rails – Rails验证防止保存
发布时间:2020-12-17 01:44:55 所属栏目:百科 来源:网络整理
导读:我有这样的用户模型: class User ActiveRecord::Base validates :password,:presence = true,:confirmation = true,:length = { :within = 6..40 } . . .end 在User模型中,我有一个我想要从OrdersController保存的billing_id列,如下所示: class OrdersCont
我有这样的用户模型:
class User < ActiveRecord::Base validates :password,:presence => true,:confirmation => true,:length => { :within => 6..40 } . . . end 在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 由于验证:用户模型中的密码,@ thisuser.save不会保存.但是,一旦我注释掉验证,@ thisuser.save就会返回true.这对我来说是一个陌生的领域,因为我认为这种验证仅在创建新用户时有效.有人可以告诉我是否验证:每次我尝试保存在用户模型时,密码应该启动?谢谢 解决方法
您需要指定何时运行验证,否则它们将在每次保存调用时运行.但这很容易限制:
validates :password,:length => { :within => 6..40 },:on => :create 另一种方法是有条件地进行此验证触发: validates :password,: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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |