我的任务是编写一个函数来验证下面代码中的名字和姓氏是不一样的。我必须使用ActiveModel :: Validation和ActiveModel :: Errors,如果两个名称相同,则应该给出错误消息“Nope”。
我的红宝石体验很少,但这是我的尝试:
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错误,因为我的函数缺少参数。我相信这可能很简单,但我真的很感激任何帮助。
答案 0 :(得分:0)
查看https://github.com/rails/rails/tree/master/activemodel了解详情:
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
答案 1 :(得分:-1)
我想出了我自己的解决方案,我一直在寻找:
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