4

"def validate"は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 

"title"検証は機能しますが、 "description"検証は機能しません。

答えて

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 
+0

動作します。しかし、私は新しいバリデーションが古いスタイルのバリデーションに追加されたものであって、それに代わるものではないと思った。 – sthapit

+1

これは、レール2.3ガイドからほぼそのまま取られました。これは古い方法です。 –

+0

古いスタイルは廃止されました。なぜなら、人々のサルが 'validate'メソッドをもう一度パッチしないようにするためです。 – iwasrobbed

0

、あなたはまた、ここに記載されているもののよう 'バリ' を追加することができます。

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 
2
class Category < ActiveRecord::Base 
    validates_presence_of :title 

    private 

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

これは動作します、なぜそれは" do "で" def "ではないのですか? – sQuijeW

+0

はブロックを使ってvalidateメソッドに注入する新しいインターフェイスのように思えます。 –

関連する問題