我应该在Rails 5中放置自定义验证器?

Lor*_*lor 14 ruby-on-rails

我正在尝试为我的应用添加电子邮件自定义验证器; 但是,我应该在哪里放置自定义验证器?(我真的不想将这个验证器类放在模型中)是否有用于验证器的cli生成器?

http://guides.rubyonrails.org/active_record_validations.html

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
      record.errors[attribute] << (options[:message] || "is not an email")
    end
  end
end

class Person < ApplicationRecord
  validates :email, presence: true, email: true
end
Run Code Online (Sandbox Code Playgroud)

自定义验证器的约定位置/路径是什么?

dev*_*voh 23

我把它们放入/app/validators/email_validator.rb,验证器将自动加载.

另外,我不知道你的情况是否属实,但你应该在表格中替换它.如果是这样,则在用户到达控制器之前进行第一次验证.

  <div class="field">
    <%= f.label :email %>
    <%= f.text_field :email, required: true %>
  </div>
Run Code Online (Sandbox Code Playgroud)

通过:

  <div class="field">
    <%= f.label :email %>
    <%= f.email_field :email, required: true %>
  </div>
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用的是spring,则必须重新启动它才能加载新路径 (2认同)
  • 在 Rails 5.2 中,`spring stop` 对我来说是必需的,否则它不会被选中。 (2认同)

dda*_*son 5

轨道 6

app/models/validators/也是容纳验证器的合理目录。

我选择这个目录而不是其他目录,因为app/validators验证器是特定于上下文的ActiveModel

应用程序/模型/person.rb

class Person < ApplicationRecord
  validates_with PersonValidator
end
Run Code Online (Sandbox Code Playgroud)

应用程序/模型/验证器/person_validator.rb

class PersonValidator < ActiveModel::Validator
  def validate(record)
    record.errors.add(:name, 'is required') unless record.name
  end
end
Run Code Online (Sandbox Code Playgroud)

配置/应用程序.rb

module ...
  class Application < Rails::Application
    config.load_defaults 6.1

    config.autoload_paths += Dir[File.join(Rails.root, 'app', 'models', 'validators')]
  end
end
Run Code Online (Sandbox Code Playgroud)

验证器的规格将放在 spec/models/validators/