LoginSignup
0
0

More than 3 years have passed since last update.

active hashを使う場合のバリデーション

Posted at

active hashを使ってプルダウンを実装する場合、プルダウンの一番上を

---

みたいにすると思う。

例えば、

class Genre < ActiveHash::Base
  self.data = [
    { id: 0, genre_id: '--' },
    { id: 1, genre_id: '悩み' },
    { id: 2, genre_id: 'エラー' },
    { id: 3, genre_id: '技術内容' },
    { id: 4, genre_id: '恋愛' },
    { id: 5, genre_id: '人間関係' },
    { id: 6, genre_id: 'キャリア' },
    { id: 7, genre_id: '家庭' },
    { id: 8, genre_id: '体調' },
    { id: 9, genre_id: '自己実現' },
    { id: 10, genre_id: 'その他' }
  ]

   include ActiveHash::Associations
   has_many :articles

  end

このようなコードの場合、id=0のデータは、テーブルに保存したくないはず。
そのようなバリデーションを設定するには、

with_options numericality: { other_than: 0 } do
    validates :genre_id
  end

このように、thanの指定を、保存したくないidを指定することで、テーブルに保存ができないようにバリデーションをしてくれる。

参考にして頂ければ、幸いである。

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