在rails中创建期间跳过一些验证,但运行其他验证

时间:2012-02-24 17:36:27

标签: ruby-on-rails ruby-on-rails-3

我希望在创建新用户时跳过少数属性的验证,例如地址,图钉,电话号码等 然而,当用户尝试编辑时,仍需要在模型中执行其他验证。我尝试使用:on => :更新,但这对我没有帮助。有什么建议 ?

我的代码:

validates :address, :presence => true, :length => { :maximum => 50 }, :on => :update 
validates :city, :presence => true, :length => { :maximum => 50 }, :on => :update 
validates :state, :presence => true, :length => { :maximum => 50 }, :on => :update 
validates :zip, :presence => true, :numericality => true, :on => :update, :length => { :is => 5 }

4 个答案:

答案 0 :(得分:5)

根据documentation,您需要做的是这样的事情。你是说这不起作用吗?

class Person < ActiveRecord::Base
  validates_presence_of :address, :on => :update
  validates_presence_of :pin,     :on => :update
end

答案 1 :(得分:3)

  

传递:validate => false.

可以跳过保存的验证过程

请注意,如果存在数据库限制,您仍会收到错误消息。 例如如果您使用rails迁移并在创建时:null => false(通过运行迁移),则实际数据库列将具有该数据库级别的限制。作为验证的好处应该在两个地方。覆盖db constrainst(即你不能)的方法是实际删除约束的迁移。

答案 2 :(得分:2)

创建记录时:

@model = Model.new(params[:model])
@model.save false

这将跳过验证。

答案 3 :(得分:2)

validates :address, :presence => true,
                      :length => { :maximum => 50 },
                      :if => :address_changed?

  validates :city, :presence => true,
                   :length => { :maximum => 50 },
                   :if => :city_changed?

  validates :state, :presence => true,
                    :length => { :maximum => 50 },
                    :if => :state_changed?

  validates :zip,   :presence => true,
                    :numericality => true,
                    :length => { :is => 5 },
                    :if => :zip_changed?

添加if =&gt; :attribute_changed?将解决问题。