Ruby ActiveModel::Validation和ActiveModel::Errors用于验证的设置函数
我的任务是编写一个函数来验证下面代码中的名字和姓氏是否不同。我必须使用ActiveModel::Validation和ActiveModel::Errors,如果这两个名称相同,则应给出错误消息“Nope” 我几乎没有ruby方面的经验,但以下是我的尝试:Ruby ActiveModel::Validation和ActiveModel::Errors用于验证的设置函数,ruby,validation,Ruby,Validation,我的任务是编写一个函数来验证下面代码中的名字和姓氏是否不同。我必须使用ActiveModel::Validation和ActiveModel::Errors,如果这两个名称相同,则应给出错误消息“Nope” 我几乎没有ruby方面的经验,但以下是我的尝试: require 'active_model' class Person include ActiveModel::Validations validate :test validates_presence_of :f
require 'active_model'
class Person
include ActiveModel::Validations
validate :test
validates_presence_of :first
validates_presence_of :last
def initialize(first, last)
@first = first
@last = last
end
def test
errors.add_to_base("Nope") if @first == @last
end
end
a = Person.new("James", "James")
b = Person.new("James")
因此,当我尝试实例化b
时,会收到一条错误消息,但这只是一个Ruby错误,因为我的函数缺少参数。我相信这可能很简单,但我真的非常感谢您的帮助 查看更多信息:
require 'active_model'
class TestValidator < ActiveModel::Validator
def validate(record)
record.errors[:base] = "First and last can't be the same" if record.first.presence == record.last.presence
end
end
class Person
include ActiveModel::Model
attr_accessor :first, :last
validates_presence_of :first, :last
validates_with TestValidator
end
p = Person.new(first: "Nick", last: "Nick")
puts p.valid? # => false
puts p.errors.full_messages # => First and last can't be the same
p = Person.new(first: "Nick", last: "Doe")
puts p.valid? # => true
需要“活动的\u模型”
类TestValidator假的
将p.errors.full_消息#=>放在第一个和最后一个不能相同
p=新的人员(第一个:“尼克”,最后一个:“Doe”)
是否将p.设为有效?#=>真的
我想出了自己的解决方案,我想要的是:
require 'active_model'
class Person
include ActiveModel::Validations
attr_accessor :first, :last
validate :first_does_not_equal_last
def first_does_not_equal_last
if @first == @last
self.errors[:base] << "First cannot be the same as Last"
end
end
def initialize(first, last)
@first = first
@last = last
end
end
需要“活动的\u模型”
班主任
包括ActiveModel::验证
属性访问器:第一,最后
验证:第一个不等于最后一个
def first不等于last
如果@first==@last
self.errors[:base]那么,问题是什么?问题是如何让函数验证两个名称是否不相同,以及如何验证第一个和第二个名称的存在?是否使用rails?还是仅仅是动态模型?无论如何,您可以传递nil
:Person.new(“James”,nil)