Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Rails Context Validation

kbaba1001
December 08, 2014

Rails Context Validation

Validation Night ( http://connpass.com/event/9982/ )

kbaba1001

December 08, 2014
Tweet

More Decks by kbaba1001

Other Decks in Technology

Transcript

  1. if オプション validates :hoge, presence: true, if: -> { first_login?

    } validates :fuga, presence: true, if: :fuga_true? def fuga_true? # ... end
  2. with_options with_options if: -> { first_login? } do |a| a.validates

    :hoge, presence: true a.validates :fuga, presence: true end
  3. 入れ子 with_options if: -> { first_login? } do |a| a.validates

    :hoge, presence: true with_options if: -> { admin? } do |b| b.validates :foo, presence: true end end
  4. 入れ子 with_options if: -> { first_login? } do |a| a.validates

    :hoge, presence: true # ここではfirst_login?が無効 with_options if: -> { admin? } do |b| b.validates :foo, presence: true end end
  5. 入れ子 with_options if: -> { first_login? } do |a| a.validates

    :hoge, presence: true # first_login? も書く必要がある with_options if: -> { first_login? && admin? } do |b| b.validates :foo, presence: true end end
  6. unlessオプション with_options if: -> { first_login? } do |a| a.validates

    :hoge, presence: true # if オプションを上書きしないで済む with_options unless: -> { !admin? } do |b| b.validates :foo, presence: true end end
  7. onオプション # Model validates :hoge, presence: true, on: :first_login validates

    :fuga, presence: true, on: :create # Controller Model.save(context: :first_login) Model.create # on: :create のバリデーションが適用される
  8. 複数指定できない # Model validates :hoge, presence: true, on: :first_login validates

    :fuga, presence: true, on: :create # Controller Model.create(context: :first_login) # これは無理 Model.save(context: [:first_login, :create]) # これも無理
  9. 複雑になると… with_options on: :create { ... } with_options on: :api

    { ... } with_options on: :web { ... } with_options on: :first_login { ... } with_options on: :withdrawn { ... } (´;ω;`)ウッ…