【问题标题】:How not to allow validation for a specific action in Rails 4如何在 Rails 4 中不允许对特定操作进行验证
【发布时间】:2015-05-20 09:23:14
【问题描述】:

我的 user.model.rb 中有这个密码验证:

class User < ActiveRecord::Base

  validates :password, presence: true, confirmation: true,
            format: {:with => /^(?=.*[0-9])(?=.*[A-Z])(?=.*[&%$#@*])[a-zA-Z0-9&%$#@*]{8,}$/,
            :multiline => true, :message => I18n.t('invalid_password')}
end

我希望在每个方法中都调用此验证,而不是在我的更新操作中。

我有一个包含创建和更新操作的 users_controller.rb。我希望它检查创建操作而不是更新操作。

我还有一个 password_resets_controller.rb,我希望它在其中检查创建和更新操作,但不检查 users_controller 更新操作。我正在使用 authlogic gem。两个控制器使用相同的模型。

请指导我如何做到这一点。提前致谢。

【问题讨论】:

标签: ruby-on-rails validation ruby-on-rails-4


【解决方案1】:
validates :password, :presence => {:on => :create}

##here new_user is a method that you can create and use condionally
## or validates_presence_of :password, :if => :new_user?
validates_presence_of :password, :unless => :new_user?

def new_user?
  //your code
end

使用with_options

class User < ActiveRecord::Base
  has_many :roles

  # Normal Validations 
  validates_presence_of   :password


  with_options :if => :customer? do |customer|
    customer.validates_presence_of :password
  end

  def customer?
    roles.any? { |role| role.name == "customer" }
  end 
end  

【讨论】:

  • 我在 users_controller.rb 更新操作 @user.update(user_params) 中有这个。我将如何跳过验证
  • 您不能在更新时跳过验证...您需要使用 update_attribute 或使用 validate:false 。试一试
  • OP 希望在模型定义中跳过验证。 update_attributes 是另外一回事——她不会询问不验证对象的方法
【解决方案2】:

最接近的答案可能是:

class User < ActiveRecord::Base
   validates :password, presence: true, if: :not_persisted?

   def not_persisted?
     !self.persisted?  
   end
end

仅当对象未持久化(创建时)时,此代码才会真正触发验证

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2023-04-06
    • 2018-09-05
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多