Rails - 如何有条件地启用验证?

时间:2011-06-10 18:20:58

标签: ruby-on-rails validation oauth authlogic

我的用户模型如下:

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

这不起作用,因为表中的“twitter_id”属性是否存在。

如何有选择地启用电子邮件和密码验证? i,e仅在未使用twitter oAuth的情况下启用验证。

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

尝试给ValidationSkipper一个镜头:

https://github.com/npearson72/validation_skipper

只需在用户模型上设置验证和条件,并在拨打Twitter时跳过它们。