5
3

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.

Active Model にカスタムバリデータを適用したい

Posted at

Active Recordなら独自のバリデーションを追加する文献がググるとたくさんあるけど、Active Modelでやる方法が見つからない・・・。

下記コードで出来ました。

例:入力された値を配列で受け取り、その配列数が4以上の場合はエラーを出すバリデーションを実装

app/model/hoge_form.rb
class HogeForm
  include ActiveModel::Model
  attr_accessor :keyword

  validates :keyword,     :presence => {message: "キーワードを入力してください"}
  validate :keyword_max

  def keyword_max
    if @keyword.count > 3
      errors[:keyword] =  '指定できるワードは3つまでです'
    end
  end
end

ActiveRecordと同じようにvalid?でバリデーションチェックが出来ます

app/controller/hoge_index.rb
form = new HogeForm(:keyword=>[1,2,3,4])
if form.valid?
  puts 'エラー'
end

余談

phpのsymfony使っているとwidgetが欲しくなる・・・
てことで、Active Modelのファイル名をxxxxForm.rbっていう共通な名前にして
widgetみたいな振る舞いにしています。他に、いい方法はないか模索中

5
3
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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?