2013-10-15 48 views
-1

我已經被授權編寫一個函數來驗證下面代碼中的名字和姓氏不一樣。我必須使用ActiveModel :: Validation和ActiveModel :: Errors,如果兩個名稱相同,它應該給出一個錯誤消息「Nope」。驗證Ruby ActiveModel ::驗證和ActiveModel :: Errors設置功能

我很少紅寶石的經驗,但這裏是我的嘗試:

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

問題是如何獲得函數來驗證這兩個名稱是不一樣的,以及如何驗證第一個和第二個名稱的存在? – James

+0

你在使用rails嗎?或者只是ActiveModel?總之,不要錯過姓氏,你可以通過'nil':'Person.new(「James」,nil)' –

回答

-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 
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 
相關問題