LoginSignup
6
6

More than 5 years have passed since last update.

特定のActiveRecordインスタンスにValidationを追加する

Posted at

特定のActiveRecordインスタンスにValidationを追加する

どんなときに使う

  • 特定の場合のみコスト高めのチェック処理をしたい場合
  • ↑によってより親切なエラーメッセージを表示したい場合

やり方

app/controler/hoge_controller.rb
class HogeController < ApplicationController
  # ...
  def create
    user = User.new(permit_params)
    @user.singleton_class.validate :validate_foobar
    user.save! # ちゃんとvalidate_foobarが実行される
  end
  # ...
end
app/models/user.rb
class User < ActiveRecord::Base
  # validates :validate_foobar は記述しない
  # ...
  def validate_foobar
    # something
  end
  # ...
end

参考

6
6
3

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