要在model中檢查,建立create/儲存save/更新update的時候檢查。
寫學習紀錄的時候,突然發現ihower好像做過了我現在做的事情,乾脆一不做二不休,把他的連結貼上來吧。呵呵。
ihower寫得很清楚歐
https://ihower.tw/rails/activerecord-lifecycle.html
app/models/post.rb 加入
validates :content, presence: true #若是content為空,就不得送出
class User <ActiveRecord::Base
has_secure_password
validates :email, format : {with: /\A[^@]+@[^@]+/\z/ } #驗證用戶輸入的email格式是否正確
validates :name, presence: true, length: {maximum: 30} #必須填入name,長度限制
end
將email資料加進index。增加搜尋速度。也避免重複登入資料
要使用migration把它加進去
$rails g migration add_email_index_to_user
修改db檔案
進入db/migrata/***add_email_index_to_user.rb
class AddEmailIndexToUser < ActiveRecord::Migration
def change
add_index :users, :email, unique: true #看起來很像add_column吧....
end
end
執行migrate更新資料庫
$ rails db:migrate
一般假如有看到錯誤,可以在rails c裡面看。
> post.errors
> post.errors.any?
> post.errors[:email]
> post.errors[:title]
寫學習紀錄的時候,突然發現ihower好像做過了我現在做的事情,乾脆一不做二不休,把他的連結貼上來吧。呵呵。
ihower寫得很清楚歐
https://ihower.tw/rails/activerecord-lifecycle.html
app/models/post.rb 加入
validates :content, presence: true #若是content為空,就不得送出
在user或是member可以用到validates驗證
app/models/user.rbclass User <ActiveRecord::Base
has_secure_password
validates :email, format : {with: /\A[^@]+@[^@]+/\z/ } #驗證用戶輸入的email格式是否正確
validates :name, presence: true, length: {maximum: 30} #必須填入name,長度限制
end
將email資料加進index。增加搜尋速度。也避免重複登入資料
要使用migration把它加進去
$rails g migration add_email_index_to_user
修改db檔案
進入db/migrata/***add_email_index_to_user.rb
class AddEmailIndexToUser < ActiveRecord::Migration
def change
add_index :users, :email, unique: true #看起來很像add_column吧....
end
end
執行migrate更新資料庫
$ rails db:migrate
錯誤資訊
錯誤資訊看是要顯示在哪裡。一般假如有看到錯誤,可以在rails c裡面看。
> post.errors
> post.errors.any?
> post.errors[:email]
> post.errors[:title]