Rails: 对多个模型使用相同的自定义验证方法
Rails: Using same custom validation method for multiple models
我在 3 个模型中都有这个方法,所以我想提取它并 DRY 东西。我对 attr 的默认值也有疑问。当字段为空时,它将被评估为空字符串 ""
而不是 nil
,因此我必须在方法中编写条件以避免将 "http" 添加到空字符串。
我应该把方法放在哪里,如何将它包含在模型中?
我应该优化方法吗?如果是这样,我在哪里以及如何将默认 attr 值设置为 nil
(rails/db/both)?
before_validation :format_website
def format_website
if website == ""
self.website = nil
elsif website.present? && !self.website[/^https?/]
self.website = "http://#{self.website}"
end
end
您可以将您的方法放在 app/models/concerns 文件夹中,例如,作为 Validatable
模块(即 validatable.rb):
module Concerns::Validatable
extend ActiveSupport::Concern
def format_website
if website.blank?
self.website = nil
elsif !self.website[/^https?/]
self.website = "http://#{self.website}"
end
end
end
然后将其包含在每个模型中作为
include Concerns::Validatable
我在 3 个模型中都有这个方法,所以我想提取它并 DRY 东西。我对 attr 的默认值也有疑问。当字段为空时,它将被评估为空字符串 ""
而不是 nil
,因此我必须在方法中编写条件以避免将 "http" 添加到空字符串。
我应该把方法放在哪里,如何将它包含在模型中?
我应该优化方法吗?如果是这样,我在哪里以及如何将默认 attr 值设置为 nil
(rails/db/both)?
before_validation :format_website
def format_website
if website == ""
self.website = nil
elsif website.present? && !self.website[/^https?/]
self.website = "http://#{self.website}"
end
end
您可以将您的方法放在 app/models/concerns 文件夹中,例如,作为 Validatable
模块(即 validatable.rb):
module Concerns::Validatable
extend ActiveSupport::Concern
def format_website
if website.blank?
self.website = nil
elsif !self.website[/^https?/]
self.website = "http://#{self.website}"
end
end
end
然后将其包含在每个模型中作为
include Concerns::Validatable