我有一個rails應用程序,我想添加驗證字符的長度。Ruby on rails創建一個驗證並在任何地方使用
它在應用程序中使用的地方有text field
,我在應用程序中有很多模型。放在模型中的任何地方似乎都是重複的。
還能有我可以做一個單一的驗證和模型任何地方使用任何方法。
我不能只是得到一點,所以我還沒有嘗試到現在 解決方案將非常感激。如果有人可以提供答案
我有一個rails應用程序,我想添加驗證字符的長度。Ruby on rails創建一個驗證並在任何地方使用
它在應用程序中使用的地方有text field
,我在應用程序中有很多模型。放在模型中的任何地方似乎都是重複的。
還能有我可以做一個單一的驗證和模型任何地方使用任何方法。
我不能只是得到一點,所以我還沒有嘗試到現在 解決方案將非常感激。如果有人可以提供答案
您可以創建一個custom validation
# app/validators/char_validator.rb
class CharValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
# your validation
end
end
# app/models/foo.rb
class Foo < ActiveRecord::Base
validates :bar, presence: true, char: true
end
我可以在關注文件夾中生成char_validator.rb嗎? – user4965201
@ user4965201'app/validators'是一個約定。否則它將無法工作。 –
順便說一下,驗證器是一個類,而不是一個模塊。你爲什麼想要關注它? –
你可以使用這個問題。你可以把你方法在app/models/concerns
文件夾,例如,因爲是Validatable模塊
module Concerns::Validatable
extend ActiveSupport::Concern
def format_website
Write your validation code here.
end
end
然後將其包含在每個模型作爲
include Concerns::Validatable
我怎麼能在這種情況下給不同的字段名稱相同的驗證? – user4965201
一種方法是使用validates_with
與自定義的驗證類一起。更多信息可在http://guides.rubyonrails.org/active_record_validations.html#validates-with
# Your custom validator. Validates that field is all capital letters
class ShoutingValidator < ActiveModel::Validator
def validate(record)
options[:fields].each do |field|
original_value = record.public_send(field).to_s
uppercase_value = original_value.upcase
if original_value != uppercase_value
record.errors.add(field, "#{field} must be shouted in all capital letters.")
end
end
end
end
# Will likely be ActiveRecord::Base in your case Only difference would be to
# remove the `include` and `attr_accessor` lines
class Book
include ActiveModel::Model
validates_with ShoutingValidator, fields: [:title, :author]
attr_accessor :title, :author
end
# Second class to show that the same custom validator can be used
# for other class and field too.
class Person
include ActiveModel::Model
validates_with ShoutingValidator, fields: [:name]
attr_accessor :name
end
# When writing it, i created a test to see that it works
describe Book do
it 'has shouting title' do
expect(described_class.new title: 'Non shout').to_not be_valid
end
end
我可以把這個shouting_validator.rb文件放在models文件夾中嗎? – user4965201
你可以將它們放到模型文件夾中,但更清晰的是將它們存儲在'app/validators'下。他們會從兩個地方自動加載。 –
可以看出是現場要驗證稱爲到處都一樣,或者你做你想做的相同的驗證邏輯應用到具有不同名稱的領域? –
相同的驗證邏輯到不同名稱的字段 – user4965201