相信從名字上就很好知道,主要在處理 form 表單打到後端時,到資料庫的驗證問題,可以先來看一先如果沒有額外拆出來通通寫在 model 內會發生的狀況,不只邏輯會變非常的長,還會發生如果到時候整個重新設計要改邏輯,其他地方也要全部一起重新驗證,甚至是把其他的驗證改壞了。
光看可能一堆的邏輯,想完就忘了,結果要邊改邏輯的時候,又再繼續想一次XDD
# model user.rb
validates :first_name, presence: true, if: :individual_required?
validates :last_name, presence: true, if: :individual_required?
# ...
def individual_required?
(!quickmode? || (quickmode? && !new_record? && confirmed? && !resetting_password?)) && individual?
end
建議拆出來的寫法,舉例來說像是把登入、登出拆成兩個 form,然後對各自的欄位做驗證,可以參考以下:
app/forms
folderapp > forms > users > sign_in_form.rb
# frozen_string_literal: true
module Users
class SignInForm
include ActiveModel::Model
attr_accessor :email, :password
validates :email, :password
end
end
# Sign in
user = Users::SignInForm.new(user_params)
sign_in(user) if user.valid?
app > forms > users > sign_up_form.rb
# frozen_string_literal: true
module Users
class SignUpForm
include ActiveModel::Model
attr_accessor :email, :password, :first_name, :last_name
validates :email, :password, :first_name, :last_name
def save
return false unless valid?
# save user
end
end
end
# Sign up
user = Users::SignUpForm.new(user_params)
user.save
也可以再 active_record_validations custom-methods