Rails Study(VIII)Validation and Errors

Rails Study(VIII)Validation and Errors

7. Working with Validation Errors
7.1 errors
Returns an OrderedHash with all errors. Each key is the attribute name and the value is an array of strings with all errors.
>>person = Person.new
=> #<Person id: nil, name: nil, created_at: nil, updated_at: nil>
>> person.errors[:name]
=> []
>> person.valid?
=> false
>> person.errors[:name]
=> ["can't be blank", "is too short (minimum is 2 characters)"]

7.2 errors[]
7.3 errors.add
The add method lets you manually add messages that are related to particular attributes.
errors.full_messages to view the messages in the form.
validate :a_method_used_for_validation_purposes
 
  def a_method_used_for_validation_purposes
    errors.add(:name, "cannot contain the characters !!!") if
      name == '!!!'
  end

>> p = Person.create(:name => "!!!")
=> #<Person id: nil, name: "!!!", created_at: nil, updated_at: nil>
>> p.errors[:name]
=> ["cannot contain the characters !!!"]
>> p.errors.full_messages
=> ["Name cannot contain the characters !!!"]

7.4 errors[:base]
No matter with the attributes, we can say the object is invalid with :base
def a_method_used_for_validation_purposes
  errors[:base] << "This person is invalid because ..."
end

7.5 errors.clear
.clear can clean all the messages.
person = Person.new
person.valid? #=> false
person.errors[:name]
# => [ "can't be blank", "is too short"]
person.errors.clear
person.errors.empty? # => true

7.6 errors.size
>> person = Person.new
=> #<Person id: nil, name: nil, created_at: nil, updated_at: nil>
i=> false
>> person.errors.size
=> 2
>> person = Person.new(:name => "carl2")
=> #<Person id: nil, name: "carl2", created_at: nil, updated_at: nil>
>> person.valid?
=> true
>> person.errors.size
=> 0

8 Displaying Validation Errors in the View
8.1 error_messages and error_messages_for
<%= form_for(@product) do |f| %>
  <%= f.error_messages %>
<% end %>

<%= error_messages_for :product %>

<%= f.error_messages :header_message => "Invalid product!",
                                 :message => "You'll need to fix the following fields:",
                                 :header_tag => :h3 %>

8.2 Customizing the Error Messages CSS
8.3 Customizing the Error Messages HTML

9 Callbacks Overview
9.1 Callback Registration
class User < ActiveRecord::Base
   validates_presence_of :login, :email

   before_validation :ensure_login_has_a_value

   protected
   def ensure_login_has_a_value
     if login.nil?
      self.login = email unless email.blank?
     end
   end
end

10 Available Callbacks
10.1 Creating an Object
before_validation
after_validation
before_save
after_save
before_create
around_create
after_create

10.2 Updating an Object
before_validation
after_validation
before_save
after_save
before_update
around_update
after_update

10.3 Destroying an Object
before_destroy
after_destroy
around_destroy

10.4 after_initialize and after_find
after_initialize
new a object, first initial an object.

after_find
first load the object from the database.

class User < ActiveRecord::Base
   def after_initialize
     puts "you have initialized an object!"
   end

   def after_find
     puts "you have found an object!"
   end
end

>>User.new
You have initialized an object!
>>User.first
You have found an object!
You have initialized an object!

11 Running Callbacks
12 Skipping Callbacks
13 Halting Execution
14 Relational Callbacks
class User < ActiveRecord::Base
  has_many :posts, :dependent => :destroy
end

class Post < ActiveRecord::Base
   after_destroy :log_destroy_action

   def log_destroy_action
     puts 'Post destroyed'
   end
end

>> user = User.first
>> user.posts.create!
>> user.destroy
Post destroyed

15 Conditional Callbacks
16 Callback Classes
17 Observers
17.1 Creating Observers
>rails generate observer Person

And there is a new file created from   app/models/person_observer.rb
class PersonObserver < ActiveRecord::Observer
  def after_create(model)
    puts "Code to send confirmation email..."
  end
end

17.2 Registering Observers
we need to register the observer in
config/application.rb
config.active_record.observers = :user_observer

17.3 Sharing Observers
We can observe more than one model
class MailerOberver < ActiveRecord::Observer
   observe :registration, :user
  
   def after_create(model)
      puts "send email"
   end
end

config.active_record.observers = :mail_observer

references:
http://guides.rubyonrails.org/active_record_validations_callbacks.html

你可能感兴趣的:(validation,Rails)