【问题标题】:Rails - How to enable validations conditionally?Rails - 如何有条件地启用验证?
【发布时间】:2011-09-12 17:19:48
【问题描述】:

我有一个看起来像这样的用户模型:

class User < TwitterAuth::GenericUser

 acts_as_authentic {|c|
   c.login_field = :email
   c.validate_email_field = false
   c.validate_password_field = false
  }
end

它使用 TwitterAuth 和 Authlogic 插件。

我想选择性地禁用验证 c.validate_email_field = false 基于用户是否使用 twitter 通过普通电子邮件注册。

- With email and password registration, the validations needs to be on.
-twitter does not have email or password fields, the validation needs to be off.

 When I disable validation, the authLogic user registration using email and password fails:

 unknown attribute: password_confirmation


 I tried to selectively disable validation if attribute 'twitter_id' is present.

 c.merge_validates_confirmation_of_password_field_options({:unless => :skip_password_validation?})

def skip_password_validation
  !attribute_present?('twitter_id')
end

这不起作用,因为无论是否使用,表 User 中都存在属性“twitter_id”。

如何选择性地启用电子邮件和密码验证? i,e 仅在不使用 twitter oAuth 时启用验证。

感谢您的帮助

【问题讨论】:

    标签: ruby-on-rails validation oauth authlogic


    【解决方案1】:

    试试 ValidationSkipper:

    https://github.com/npearson72/validation_skipper

    只需在 User 模型上设置验证和条件,然后在调用 twitter 时跳过它们。

    【讨论】:

      【解决方案2】:

      我认为您可能需要查看其他验证方法,例如用于更复杂验证逻辑的 validates_with。然后,您应该能够根据传入的内容验证所需的属性。

      【讨论】:

      • 看起来 validates_with 仅适用于 Rails 3.0。不幸的是,我在 2.3.5 上,这似乎不是一个选择。
      • 是的,你是对的。在 2.3.x 中,我想您必须直接覆盖 validate 方法。查看ActiveRecord::Validations 的示例。祝你好运!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      • 1970-01-01
      • 2011-02-23
      相关资源
      最近更新 更多