【问题标题】:Has "def validate" been taken out in Rails 3.1?Rails 3.1 中删除了“def validate”吗?
【发布时间】:2011-08-08 05:26:03
【问题描述】:

Rails 3.1 中是否删除了“def validate”?我在 Rails 3.1 pre 上,它似乎没有工作

class Category < ActiveRecord::Base
  validates_presence_of :title

  private 

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

“标题”验证有效,但“描述”验证无效。

【问题讨论】:

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


    【解决方案1】:

    这样的事情对你有用吗?

    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
    

    【讨论】:

    • 行得通。但我认为新的验证是对旧式验证的补充,而不是替代。
    • 这几乎是从 Rails 2.3 指南中逐字逐句提取的。这是老办法。
    • 旧样式已被弃用,因为他们不希望人们再修补 validate 方法
    【解决方案2】:
    class Category < ActiveRecord::Base
      validates_presence_of :title
    
      private 
    
      validate do
        errors.add(:description, "is too short") if (description.size < 200)
      end 
    end
    

    【讨论】:

    • 似乎是一个新接口,使用块注入到验证方法中,而不是直接重载它。
    【解决方案3】:

    对于其他类型的验证,您还可以添加此处列出的“验证器”:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-22
      • 2015-08-24
      相关资源
      最近更新 更多