LoginSignup
21
21

More than 5 years have passed since last update.

[Rails]条件でバリデーションをまとめる

Last updated at Posted at 2015-05-27

条件によってバリデーションの内容を変更したい時、with_optionsを使えば簡単にまとめることができる。

使い方

例)店舗検索を条件によってフォーム内容を変更する場合
1. 現在地から検索(緯度経度)
2. 店舗名から検索(ワード)
3. 都道府県から検索(都道府県と市町村を選択)

model
# 現在地から検索
with_options if: :location? do |v|
  v.validates :lat, presence: true
  v.validates :lon, presence: true
end

# 店舗名から検索
with_options if: :shop_name? do |v|
  v.validtes :word, length: { in: 2..20 }
end

# 都道府県から検索
with_options if: :area? do |v|
 v.validates :pref, presence: true
 v.validates :city, presence: true
end

rails4.2では少し簡略して書くことができます。

model
with_options if: :location? do
  validates :lat, presence: true
  validates :lon, presence: true
end

注意点

with_optionsの中でさらにifを定義した場合

model
with_options if: :location? do
  validates :lat, presence: true
  validates :lon, presence: true, if: :lat
end

上記のような場合、with_optionsブロック内のifで上書きされてしまいうまく動作しません。
with_optionsのブロック内ではif,unlessオプションは使わない方がいいです。
やむをえず使用する場合はwith_optionsで定義したものと逆のものを使います。

model
with_options if: :location? do
  validates :lat, presence: true
  validates :lon, presence: true, unless: 'lat.blank?'
end
21
21
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
21
21