有没有一种方法可以在不与数据库交互的情况下使用Rails模型进行验证?在没有数据库交互的情况下使用Rails模型
我会使用控制台生成模型并将其与Active Record验证一起使用吗?
我试图用它来验证CSV导入,使用模型验证,然后以另一种CSV格式输出。
这是在没有数据库交互的情况下完成的,但我认为需要进行验证,使用模型将是减少错误发生的好方法。
有没有一种方法可以在不与数据库交互的情况下使用Rails模型进行验证?在没有数据库交互的情况下使用Rails模型
我会使用控制台生成模型并将其与Active Record验证一起使用吗?
我试图用它来验证CSV导入,使用模型验证,然后以另一种CSV格式输出。
这是在没有数据库交互的情况下完成的,但我认为需要进行验证,使用模型将是减少错误发生的好方法。
。看看ActiveModel
例如专为验证(从上述文档拍摄)
class Person
include ActiveModel::Validations
attr_accessor :first_name, :last_name
validates_each :first_name, :last_name do |record, attr, value|
record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
end
end
person = Person.new
person.first_name = 'zoolander'
person.valid? # => false
是的,你可以做到这一点,让我们假设你有一个Person类,比你可以这样做:
class Person
attr_accessor :name, :age
include ActiveRecord::Validations
include ActiveModel::Validations
validates_presence_of :name
end