0

ログイン、メール、パスワードなどのフィールドにデフォルトでいくつかの検証 (長さ、一意性、形式など) を行う Authlogic を使用しています。

たとえば、別の属性が存在する場合、属性の 1 つに関連付けられているすべての検証をスキップできるようにしたいと考えています。

これは可能ですか?何かのようなもの:

validate :email, :unless => :has_openid?

これにより、email 属性だけの形式、長さ、および一意性の検証がスキップされます。

Rails 3.1.x アプリと authlogic 3.1.0 を使用しています。

更新: この記事に従おうとしましたが、正しく動作しませんでした: http://erikonrails.snowedin.net/?p=242

4

2 に答える 2

0

私がauthlogicでこれを行った方法は、ブロックをに渡すことacts_as_authenticです:

acts_as_authentic do |config|
  with_options :unless => :has_openid? do      
    config.merge_validates_format_of_email_field_options
    config.merge_validates_length_of_email_field_options
    config.merge_validates_uniqueness_of_email_field_options
  end
end
于 2012-06-29T22:25:03.513 に答える
0

私は回避策を書き、それを宝石に抽象化しました: https://github.com/synth/conditional_attribute_validator

Gemfile:

gem 'conditional_attribute_validator', :git => "git://github.com/synth/conditional_attribute_validator.git"

例:

class User
  include ConditionalAttributeValidator

  validate_attributes_with_condition :login, :password, :password_confirmation, :unless => :has_another_form_of_authentication?
end

ソース:

def validate_attributes_with_condition(*args)
  opts = args.extract_options!
  raise "Must have an :if or :unless option" unless opts.has_key?(:if) or opts.has_key?(:unless)

  merge_methods = self.methods.grep(/merge_.*_options/)
  args.each do |field|
    merge_methods.grep(/#{Regexp.quote(field)}/).each do |m|
      self.send(m, opts)
    end
  end
end

Rails は、オプションを既存の検証にマージするために、指定された検証に基づいてmerge_ attr _options メソッドを自動的に作成します。したがって、これらのメソッドを検索して繰り返し処理し、そのメソッドが特定のフィールドに適用されるかどうかを確認します。その場合は、 merge_attr_optionsメソッドを呼び出してオプションを渡します。

これは初期化時に実行されるだけなので、パフォーマンスについてはあまり心配していません。

于 2012-07-02T23:52:55.473 に答える