Rails 3.1中是否已取消“def验证”?

时间:2011-08-08 05:26:04

标签: ruby-on-rails ruby-on-rails-3 validation activerecord ruby-on-rails-3.1

Rails 3.1中是否已取消“def validate”?我在Rails 3.1之前,它似乎没有工作

class Category < ActiveRecord::Base
  validates_presence_of :title

  private 

  def validate
    errors.add(:description, "is too short") if (description.size < 200)
  end 
end

“标题”验证有效,但“描述”验证不起作用。

3 个答案:

答案 0 :(得分:11)

这样的事情对你有用吗?

class Category < ActiveRecord::Base
  validates_presence_of :title
  validate :description_length

  def description_length
    errors.add(:description, "is too short") if (description.size < 200)
  end 
end

答案 1 :(得分:2)

class Category < ActiveRecord::Base
  validates_presence_of :title

  private 

  validate do
    errors.add(:description, "is too short") if (description.size < 200)
  end 
end

答案 2 :(得分:0)

对于其他类型的验证,您还可以添加“Validators”,如下所示:

http://edgeguides.rubyonrails.org/3_0_release_notes.html#validations

class TitleValidator < ActiveModel::EachValidator
  Titles = ['Mr.', 'Mrs.', 'Dr.']
  def validate_each(record, attribute, value)
    unless Titles.include?(value)
      record.errors[attribute] << 'must be a valid title'
    end
  end
end

class Person
  include ActiveModel::Validations
  attr_accessor :title
  validates :title, :presence => true, :title => true
end

# Or for Active Record

class Person < ActiveRecord::Base
  validates :title, :presence => true, :title => true
end