- 浏览: 2500716 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
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(VII)Validations and Callbacks
1. The Object Life Cycle
Validations allow you to ensure that only valid data is stored in database.
Callbacks and observers allow you to trigger logic before or after an alteration of an object's state.
2. Validations Overview
2.1 Why Use Validations?
native database constraints,
client-side validations,
controller-level validations,
model-level validations
2.2 When Does Validation Happen?
>rails generate model Person name:string
>rake db:migrate
It really strange, the newly created table named People, the model class named person.rb.
Open rails console and have a test
>rails console
> p = Person.new(:name => 'Carl')
=> #<Person id: nil, name: "Carl", created_at: nil, updated_at: nil>
> p.new_record?
=> true
> p.save
[1m[36mSQL (13.0ms)[0m [1mBEGIN[0m
[1m[35mSQL (701.0ms)[0m INSERT INTO `people` (`created_at`, `name`, `updat
ed_at`) VALUES (?, ?, ?) [["created_at", Fri, 05 Aug 2011 06:04:37 UTC +00:00],
["name", "Carl"], ["updated_at", Fri, 05 Aug 2011 06:04:37 UTC +00:00]]
[1m[36m (1.0ms)[0m [1mCOMMIT[0m
=> true
> p.new_record?
=> false
There are 2 kinds of objects. One is saved in database, one has no relationship with database yet.
2.3 Skipping Validations
save(:validate => false)
2.4 valid? and invalid?
class Person < ActiveRecord::Base
validates :name, :presence =>true
end
> Person.create(:name=>"carl").valid?
=> true
> Person.create(:name=>nil).valid?
=> false
>>p = Person.new
>>p.valid?
=>false
>>p.errors
=>{:name=>["can't be blank"]}
2.5 errors[]
errors[:attribute], it returns an array of all the errors for :attribute.
>>Person.new.errors[:name].any?
=> false
>>Person.create.errors[:name].any?
=> true
>>Person.create.errors[:name]
=> ["can't be blank"]
3. Validation Helpers
3.1 validates_acceptance_of
Validates that a checkbox on the user interface was checked when a form was submitted.
validates_acceptance_of :terms_of_service
3.2 validates_associated
has_many :books
validates_associated :books
3.3 validates_confirmation_of
We need to use this helper when we have 2 text fields that should receive exactly the same content.
class Person < ActiveRecord::Base
validates_confirmation_of :email
validates_presence_of :email_
end
<%= text_field :person, :email %>
<%= text_field :person, :email_confirmation %>
3.4 validates_exclusion_of
3.5 validates_format_of
validates_format_of :legacy_code, :with => /\A[a-zA-Z]+\z/, :message => "only leters allowed"
3.6 validates_inclusion_of
3.7 validates_length_of
validates_length_of :name, :minimum =>2
validates_length_of :name, :maximum => 500
validates_length_of :password, :in => 6..20 #:in(or :within) the attribute length must be included in a given interval.
validates_length_of :registration_number, :is => 6 # the attribute length must be equal to the given value
validates_length_of :bio, :maximum =>1000, :too_long => "%{count} characters is the maximum allowed"
3.8 validates_numericality_of
validates_numericality_of :points
validates_numericality_of :games_played,nly_integer => true
:greater_than
:greater_than_or_equal_to
:equal_to
:less_than
:less_than_or_equal_to
:odd
:even
3.9 validates_presence_of
class Person < ActiveRecord::Base
validates_presence_of :name
end
>>Person.create.valid?
=> false
>>Person.create(:name=>'joan').valid?
=> true
validates_presence_of :name, :login, :email
3.10 validates_uniqueness_of
validates_uniqueness_of :email
validates_uniqueness_of :name :case_sensitive => false
3.11 validates_with
3.12 validates_each
4. Common Validation Options
4.1 :allow_nil
4.2 :allow_blank
4.3 :message
4.4n
Then option lets you specify when the validation should happen.
class Person < ActiveRecord::Base
validates_uniqueness_of :email,n => :create
validates_numericality_of :age,n => :update
validates_presence_of :name,n => :save
end
5. Conditional Validation
5.1 Using a Symbol with :if and :unless
class Order < ActiveRecord::Base
validates_presence_of :card_number, :if => :paid_with_card?
def paid_with_card?
payment_type == "card"
end
end
5.2 Using a String with :if and :unless
validates_presence_of :surname, :if => "name.nil?"
5.3 Using a Proc with :if and :unless
6 Creating Custom Validation Methods
class Invoice < ActiveRecord::Base
validate :expiration_date_cannot_be_in_the_past,
:discount_cannot_be_greater_than_total_value
def expiration_date_cannot_be_in_the_past
errors.add(:expiration_date, "can't be in the past") if
!expiration_date.blank? and expiration_date < Date.today
end
def discount_cannot_be_greater_than_total_value
errors.add(:discount, "can't be greater than total value") if
discount > total_value
end
end
references:
http://guides.rubyonrails.org/active_record_validations_callbacks.html
1. The Object Life Cycle
Validations allow you to ensure that only valid data is stored in database.
Callbacks and observers allow you to trigger logic before or after an alteration of an object's state.
2. Validations Overview
2.1 Why Use Validations?
native database constraints,
client-side validations,
controller-level validations,
model-level validations
2.2 When Does Validation Happen?
>rails generate model Person name:string
>rake db:migrate
It really strange, the newly created table named People, the model class named person.rb.
Open rails console and have a test
>rails console
> p = Person.new(:name => 'Carl')
=> #<Person id: nil, name: "Carl", created_at: nil, updated_at: nil>
> p.new_record?
=> true
> p.save
[1m[36mSQL (13.0ms)[0m [1mBEGIN[0m
[1m[35mSQL (701.0ms)[0m INSERT INTO `people` (`created_at`, `name`, `updat
ed_at`) VALUES (?, ?, ?) [["created_at", Fri, 05 Aug 2011 06:04:37 UTC +00:00],
["name", "Carl"], ["updated_at", Fri, 05 Aug 2011 06:04:37 UTC +00:00]]
[1m[36m (1.0ms)[0m [1mCOMMIT[0m
=> true
> p.new_record?
=> false
There are 2 kinds of objects. One is saved in database, one has no relationship with database yet.
2.3 Skipping Validations
save(:validate => false)
2.4 valid? and invalid?
class Person < ActiveRecord::Base
validates :name, :presence =>true
end
> Person.create(:name=>"carl").valid?
=> true
> Person.create(:name=>nil).valid?
=> false
>>p = Person.new
>>p.valid?
=>false
>>p.errors
=>{:name=>["can't be blank"]}
2.5 errors[]
errors[:attribute], it returns an array of all the errors for :attribute.
>>Person.new.errors[:name].any?
=> false
>>Person.create.errors[:name].any?
=> true
>>Person.create.errors[:name]
=> ["can't be blank"]
3. Validation Helpers
3.1 validates_acceptance_of
Validates that a checkbox on the user interface was checked when a form was submitted.
validates_acceptance_of :terms_of_service
3.2 validates_associated
has_many :books
validates_associated :books
3.3 validates_confirmation_of
We need to use this helper when we have 2 text fields that should receive exactly the same content.
class Person < ActiveRecord::Base
validates_confirmation_of :email
validates_presence_of :email_
end
<%= text_field :person, :email %>
<%= text_field :person, :email_confirmation %>
3.4 validates_exclusion_of
3.5 validates_format_of
validates_format_of :legacy_code, :with => /\A[a-zA-Z]+\z/, :message => "only leters allowed"
3.6 validates_inclusion_of
3.7 validates_length_of
validates_length_of :name, :minimum =>2
validates_length_of :name, :maximum => 500
validates_length_of :password, :in => 6..20 #:in(or :within) the attribute length must be included in a given interval.
validates_length_of :registration_number, :is => 6 # the attribute length must be equal to the given value
validates_length_of :bio, :maximum =>1000, :too_long => "%{count} characters is the maximum allowed"
3.8 validates_numericality_of
validates_numericality_of :points
validates_numericality_of :games_played,nly_integer => true
:greater_than
:greater_than_or_equal_to
:equal_to
:less_than
:less_than_or_equal_to
:odd
:even
3.9 validates_presence_of
class Person < ActiveRecord::Base
validates_presence_of :name
end
>>Person.create.valid?
=> false
>>Person.create(:name=>'joan').valid?
=> true
validates_presence_of :name, :login, :email
3.10 validates_uniqueness_of
validates_uniqueness_of :email
validates_uniqueness_of :name :case_sensitive => false
3.11 validates_with
3.12 validates_each
4. Common Validation Options
4.1 :allow_nil
4.2 :allow_blank
4.3 :message
4.4n
Then option lets you specify when the validation should happen.
class Person < ActiveRecord::Base
validates_uniqueness_of :email,n => :create
validates_numericality_of :age,n => :update
validates_presence_of :name,n => :save
end
5. Conditional Validation
5.1 Using a Symbol with :if and :unless
class Order < ActiveRecord::Base
validates_presence_of :card_number, :if => :paid_with_card?
def paid_with_card?
payment_type == "card"
end
end
5.2 Using a String with :if and :unless
validates_presence_of :surname, :if => "name.nil?"
5.3 Using a Proc with :if and :unless
6 Creating Custom Validation Methods
class Invoice < ActiveRecord::Base
validate :expiration_date_cannot_be_in_the_past,
:discount_cannot_be_greater_than_total_value
def expiration_date_cannot_be_in_the_past
errors.add(:expiration_date, "can't be in the past") if
!expiration_date.blank? and expiration_date < Date.today
end
def discount_cannot_be_greater_than_total_value
errors.add(:discount, "can't be greater than total value") if
discount > total_value
end
end
references:
http://guides.rubyonrails.org/active_record_validations_callbacks.html
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 445NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 302Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 390Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 350Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 433NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 381Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 309Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 221GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 407GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 286GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 281Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 279Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 263Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 252Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 250NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 237Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 533NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 238Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 334Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 331Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
Wrangle Forms and Validations with Angular Chapter 13. Dig Deeper Appendix A1. Full Listing of Customer Detail Page HTML Appendix A2. Creating Customer Address Seed Data Appendix A3. How Webpack ...
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),电子书实战版
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删除
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. ☆ 出版信息:☆ [作者...
NetBeans Ruby and Rails IDE with JRuby 2009,大家看标题就知道了啊。。好东西啊,刚得到就发上来了。。
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 ...
The Rails™ 3 Way is a comprehensive resource that digs into the new features in Rails 3 and perhaps more importantly, the rationale behind them. —Yehuda Katz, Rails Core The Bible for Ruby on ...
Now in version 4, Rails is mature and powerful, and to use it effectively you need more than a few Google searches. You'll find no substitute for the guru's-eye-view of design, testing, deployment, ...
This short early adopter book details both how you’ll upgrade existing web and other applications from Rails 4.2 to 5 and how to create new applications in Rails 5. The headline features, Rails API ...