11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsでデータを削除する際にバリデーションをかける

Last updated at Posted at 2018-02-05

dependent: :restrict_with_errors

はじめに

データを保存する時であれば、

validates :column, presence: true

などでバリデーションをかけられますが、今回はデータを削除する時にバリデーションをかけたかったので実装しました。

実装

Userstatusstopped でなければ削除できないというコードを書きます。

app/models/user.rb
class User < ApplicationRecord
  STATUS_STOPPED = 'stopped'.freeze

  before_destroy :validate_status_stopped

  private
    def validate_status_stopped
  	  errors.add :base, 'ユーザーステータスが停止になっていません。'
  	  throw(:abort) if self.status == STATUS_STOPPED
    end
end

子要素の存在有無でバリデーションをかける場合

User が複数の Articlehas_many している時に、Article と紐付いている間は削除できないようにする場合、

微妙な解決策

app/models/user.rb
class User < ApplicationRecord
  has_many :articles
  
  before_destroy :validate_article_presence
  
  private
  	def validate_article_presence
  	  errors.add :base, 'まだ記事が残っています。'
  	  throw(:abort) if self.articles.blank?
  	end
end

上記コードでもちゃんと動作はしますが、before_destroy を書いたり、そのためにメソッドも作らなければいけません。
子要素の有無で削除する際にバリデーションをかける場合は下記のコードで動きます。

app/models/user.rb
class User < ApplicationRecord
  has_many :articles, dependent: :restrict_with_error
end

これだけでちゃんと動くようになる!
似たような名前で restrict_with_exception というやつがいますが、それとの違いはこちらの記事で詳しくまとまってます。

まとめ

上記でデータを削除する際にバリエーションをかける時ができますので使ってみてください!

11
6
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
11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?