开发网站的时候,资料验证非常重要,我们都不希望有一些奇怪的资料塞在里面,所以我们要做验证!
我在书上看到下面3大重点,来笔记一下吧:
- 前端验证:在HTML页面使用JavaScript在使用者填写资料的时候检查
1.接下来我们,在Product Model希望每个商品的name都为必填,资讯可以这样写:
class Product < ApplicationRecord
has_many :planet
has_many :stores, through: :planet
validates :name, presence: true
end
2.validates :name, presence: true
意思是 name这个栏位为必填栏位
3.接着,我们开rails c起来试试看:
w1 = Product.new
(0.5ms) SELECT sqlite_version(*)
=> #<Product id: nil, name: nil, description: nil, price: nil, is_available: nil, store_id: nil, cre...
4.先用new
方法建立一个Product物件,用errors
这个方法来看这物件有没有什麽状况?
> w1.errors.any?
=> false
5.看起来没有什麽问题,接着我们使用save
方法,把这个物件存入资料表中:
> w1.save
=> false
6.但依照我们看到的情况下,好像失败了,回传了false
回来,接下来我们比需看看是什麽问题?
> w1.errors.any?
=> true
7.以上面来看是没有问题,但在下了save
这个方法之後就会有问题,所以我们必须知道错误讯息是什麽?
> w1.errors.full_messages
=> ["Name can't be blank"]
我们可以看到他上面写Name不可以是空白!
那验证没过的时候,该怎麽办?
当我们看到资料验证没有过关的时候,我们可以透过物件本身有errors
的方法得知。
进入rails c
我们先做一个Product新物件,其中name
栏位必填栏位:
> product1 = Product.new
(0.3ms) SELECT sqlite_version(*)
=> #<Product id: nil, name: nil, description: nil, price: nil, is_available: nil, store_id: nil, cre...
接着,我们呼叫save
方法,把这笔资料写进资料表内:
> product1.save
=> false
看来是失败了!!!!
这时,我们透过errors
方法来看看哪边有错误?
记得下一步还要用full_messages
错误信息印出来,这样才会明确的知道资料是在哪边出了问题!
> product1.errors
=> #<ActiveModel::Errors:0x0000000125175fb8 @base=#<Product id: nil, name: nil, description: nil, price: nil, is_available: nil, store_id: nil, created_at: nil, updated_at: nil>, @errors=[#<ActiveModel::Error attribute=name, type=blank, options={}>]>
> product1.errors.full_messages
=> ["Name can't be blank"]
是因为你的name这格栏位没有填写!
今天就分享到这边!麻瓜日记渐渐到了尾,即使要结束了,仍旧会继续努力!!!!
参考资料:为自己学Ruby on Rails
>>: [Day 29] Reactive Programming - RSocket (Hello World) Part 1
利用Day 13的collection public function getData(){ ret...
前言 今天要聊到的是 Task 把超过自己承载能力的任务放入 TP 交给别条 thread 执行的过...
Background 如同前一章节的import一样,在Go的世界当中是不允许浪费任何资源的,因此只...
Command and Control 攻击者已经进入工控环境之後,从自己的服务器传送指令给受害主机...
前言 前几天我们讲到的都是关於虚拟记忆体的资讯,包含VMA的结构,malloc() , mmap()...