Closed3

Rails(ActiveRecord)、削除時のバリデーション

がひゅーがひゅー

↓ だと user.destroy でバリデーションは呼ばれない

models/user.rb
class User < ApplicationRecord
  acts_as_paranoid
  enum account_type: {
    general: 'general',
    administrator: 'administrator'
  }
  validate :validate_deleteable

  def validate_deleteable
    if self.deleted_at.present? && self.administrator?
      errors.add(:base, :cannot_delete_administrator)
    end
  end

end
がひゅーがひゅー

結局、before_destroy に書いた

models/user.rb
class User < ApplicationRecord

  enum account_type: {
    general: 'general',
    administrator: 'administrator'
  }

  before_destroy do
    if self.administrator?
      errors.add :base, :cannot_delete_administrator 
      throw(:abort)
    end
  end
end
spec/models/user_spec.rb
require 'rails_helper'

RSpec.describe User, type: :model do

  describe 'validation' do
    subject { build(:user) }

    describe 'delete' do
      it 'is valid with not account_type administrator' do
        subject.general!
        subject.destroy
        expect(subject).to be_valid
      end
      it 'is invalid with account_type administrator' do
        subject.administrator!
        subject.destroy
        expect(subject.errors.of_kind?(:base, :cannot_delete_administrator)).to be true
      end
    end
  end

end

root@e8970daf8da5:/app# bundle exec rspec spec/models/user_spec.rb 

User
    delete
      is valid with not account_type administrator
      is invalid with account_type administrator

Finished in 0.31546 seconds (files took 16.8 seconds to load)
3 examples, 0 failures

このスクラップは2022/01/25にクローズされました