Skip to content

Instantly share code, notes, and snippets.

@mrk21
Created October 3, 2019 09:43
Show Gist options
  • Save mrk21/7be0ec1c972e794a43403b70dd67ac5a to your computer and use it in GitHub Desktop.
Save mrk21/7be0ec1c972e794a43403b70dd67ac5a to your computer and use it in GitHub Desktop.
Validation on destroying for Rails
# frozen_string_literal: true
class HogesController < ApplicationController
def destroy
hoge = Hoge.find(params[:id])
hoge.destroy!
redirect_to hoges_path
rescue ActiveRecord::RecordNotDestroyed => e
flash[:error] = e.record.errors.full_messages.join("\n")
flash[:error] = 'Destroying failed' if flash[:error].blank?
redirect_to hoges_path
end
end
# frozen_string_literal: true
class Hoge < ApplicationRecord
before_destroy :validate_for_destroy
def can_destroy?
is_completed_initialization? && !is_finished?
end
def is_completed_initialization?
...
end
def is_finished?
...
end
private
def validate_for_destroy
return if can_destroy?
errors.clear
errors.add :base, :'destroy.has_not_completed_initialization_yet' unless is_completed_initialization?
errors.add :base, :'destroy.finished' if is_finished?
throw :abort
end
end
ja:
activerecord:
errors:
models:
hoge:
attributes:
base:
destroy:
has_not_completed_initialization_yet: It has not completed initialization yet
finished: It was already finished
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment