0

如何在 rails 3.2 中验证全名的唯一性?

class User < ActiveRecord::Base
    attr_accessible :first_name, :last_name

    validates :name, :uniqueness => true

    def name
        [first_name, last_name].join(' ')
    end
end

当我运行 rspec 时,测试失败并出现此错误。

  1) User has a first name
     Failure/Error: before { @user = FactoryGirl.create(:user) }
     NoMethodError:
       undefined method `text?' for nil:NilClass
4

1 回答 1

1

解决方案1:

validates :first_name, :uniqueness => { :scope => :last_name, :message => "name is uniq" }

解决方案2:

class Person < ActiveRecord::Base
  validates_with GoodnessValidator, :fields => [:first_name, :last_name]
end

class GoodnessValidator < ActiveModel::Validator
  def validate(record)
    if options[:fields].any?{|field| record.send(field) == "Evil" }
      record.errors[:base] << "This person is evil"
    end
  end
end
于 2012-12-12T05:42:51.047 回答