ubuntu, ror, jQuery, css, website memo
太嫩, 沒啥心得, 用來紀錄每天學的
2008年11月18日 星期二
validate,valid?
http://api.rubyonrails.org/classes/ActiveRecord/Validations.html#M001627
class Person < ActiveRecord::Base
protected
def validate
errors.add_on_empty %w( first_name last_name )
errors.add("phone_number", "has invalid format") unless phone_number =~ /[0-9]*/
end
def validate_on_create # is only run the first time a new object is saved
unless valid_discount?(membership_discount)
errors.add("membership_discount", "has expired")
end
end
def validate_on_update
errors.add_to_base("No changes have occurred") if unchanged_attributes?
end
end
person = Person.new("first_name" => "David", "phone_number" => "what?")
person.save # => false (and doesn't do the save)
person.errors.empty? # => false
person.errors.count # => 2
person.errors.on "last_name" # => "can't be empty"
person.errors.on "phone_number" # => "has invalid format"
person.errors.each_full { |msg| puts msg }
# => "Last name can't be empty\n" +
"Phone number has invalid format"
person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" }
person.save # => true (and person is now saved in the database)
沒有留言:
張貼留言
較新的文章
較舊的文章
首頁
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言