0
0

More than 1 year has passed since last update.

【FormObject】バリデーションpresenceとuniquenessをどこに書くか

Last updated at Posted at 2021-11-09

環境

Ruby 3.0.2
Rails 6.1.4.1

FormObject

バリデーションの記述はModelではなくFormObjectに切り出したほうがよいという内容の記事を見つけた。

ActiveModel::ModelをincludeしてればModel同様にバリデーションを書ける。
バリデーションpresenceはFormObjectに切り出す。

app/forms/employee_form.rb
class EmployeeForm
  include ActiveModel::Model

  with_options presence: true do
    validates :firstname
    validates :lastname
  end
end

バリデーションuniquenessはDBとやり取りして判定するバリデーションのため、Modelの方に書く。

app/models/employee.rb
class Employee < ApplicationRecord
  validates :number, presence: true, uniqueness: true
  validates :email, presence: true, uniqueness: true
end

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0