iT邦幫忙

2021 iThome 鐵人賽

DAY 29
0
自我挑戰組

海邊囝仔帶阿公阿嬤一起學 Ruby On Rails 系列 第 29

Day-29 : Model驗證

開發網站的時候,資料驗證非常重要,我們都不希望有一些奇怪的資料塞在裏面,所以我們要做驗證!

我在書上看到下面3大重點,來筆記一下吧:

  1. 前端驗證:在HTML頁面使用JavaScript在使用者填寫資料的時候檢查
  1. 後端驗證:資料上傳到伺服器後,在寫入資料庫的時候由網站應用程式進行檢查
  2. 資料庫驗證:直接由資料庫本身所提供的功能來做資料驗證

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這格欄位沒有填寫!

今天就分享到這邊!麻瓜日記漸漸到了尾,即使要結束了,仍舊會繼續努力!!!!/images/emoticon/emoticon08.gif

參考資料:為自己學Ruby on Rails


上一篇
Day-28 : Model 多對多
下一篇
Day-30: 設計轉工程師這趟旅程,一些感言
系列文
海邊囝仔帶阿公阿嬤一起學 Ruby On Rails 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言