Created
October 3, 2019 09:43
-
-
Save mrk21/7be0ec1c972e794a43403b70dd67ac5a to your computer and use it in GitHub Desktop.
Validation on destroying for Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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