gpt4 book ai didi

ruby-on-rails - 我应该将自定义验证器放在 Rails 5 中的什么位置?

转载 作者:行者123 更新时间:2023-12-03 21:23:31 25 4
gpt4 key购买 nike

我正在尝试为我的应用添加电子邮件自定义验证器;但是,我应该在哪里放置自定义验证器? (我真的不想把这个验证器类放在模型中)验证器有 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

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

最佳答案

rails 6app/models/validators/也是存放验证器的明智目录。
我选择此目录而不是其他目录,例如 app/validators因为验证器是特定于 ActiveModel 的上下文
应用程序/模型/person.rb

class Person < ApplicationRecord
validates_with PersonValidator
end
应用程序/模型/验证器/person_validator.rb
class PersonValidator < ActiveModel::Validator
def validate(record)
record.errors.add(:name, 'is required') unless record.name
end
end
配置/应用程序.rb
module ...
class Application < Rails::Application
config.load_defaults 6.1

config.autoload_paths += Dir[File.join(Rails.root, 'app', 'models', 'validators')]
end
end
验证器的规范将放在 spec/models/validators/

关于ruby-on-rails - 我应该将自定义验证器放在 Rails 5 中的什么位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42253003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com