- 浏览: 2503579 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
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
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
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 446NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 303Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 391Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 353Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 436NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 383Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 311Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 223GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 409GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 289GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 286Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 280Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 266Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 254Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 251NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 238Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 536NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 239Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 335Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 336Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
You should have some experience with basic Rails concepts and a cursory understanding of JavaScript, CSS, and SQL, but by no means need to be an expert. You'll learn how to install Postgres on your ...
This concise teaches you how to use the power of Docker and Kubernetes to deploy your Rails applications easily and efficiently. Docker and Kubernetes are increasing in popularity every day, but what ...
RUBY的经典之作,对其在RAILS下开发写得很详细
ruby.on.rails.up.and.running
Rails, Angular, Postgres, and Bootstrap(2nd),电子书实战版
Testing lessons show you how to eliminate cross-browser JavaScript errors and DOM debugging nightmares using a combination of Firebug, and Venkman. Advanced material explains the most current design ...
Chapter 5: Reinventing Tables and Forms in Bootstrap 73 Creating Bootstrap tables 73 Creating Bootstrap forms 79 Validation classes in Bootstrap forms 84 Adding Bootstrap table a to our Rails ...
jquery-validation-rails, 对 Rails 资产管道的jQuery验证 :: 验证:: rails针对 Rails 资产管道的验证 。安装这里 gem将以下行添加到项目的Gemfile 中:gem 'jquery-validation-rails'在你的终端中运行以下命令:cd...
This pioneering book is the first resource that deep dives into the new Rails 3 APIs and shows you how use them to write better web applications and make your day-to-day work with Rails more ...
You concentrate on creating the application, and Rails takes care of the details., Tens of thousands of developers have used this award-winning book to learn Rails. It’s a broad, far-reaching ...
Ruby on Rails strips complexity from the development process, enabling professional developers to focus on what matters most: delivering business value via clean and maintainable code. The Rails™ 3 ...
rails-angular-postgres-and-bootstrap-second-edition 英文原版
这个扩展允许您创建任何自定义形状的轨道,然后将一个购物车附加到它,并实际骑在轨道上。让平台在受到撞击时能滑动,地铁列车撞到障碍物,坏掉的电梯,过山车,看不见的飞行路线,火箭推进的火车等等!...
Ruby on Rails: Up and Running
Rails, Angular, Postgres, and Bootstrap(2nd) 英文epub 第2版 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
NetBeans Ruby and Rails IDE with JRuby 2009,大家看标题就知道了啊。。好东西啊,刚得到就发上来了。。
Your Ruby on Rails ...This new edition has been updated to Rails 5.2 and RSpec 3.7 and contains full coverage of new Rails features, including system tests and the Webpack-based JavaScript setup.
This second edition of the bestselling Crafting Rails Applications has been updated to Rails 4 and discusses new topics such as streaming, mountable engines, and thread safety. ☆ 出版信息:☆ [作者...
learn how to create something visible with Rails before reaching the more difficult database models and controller code. With Learning Rails, you can start from the foundations of web design you ...