概要
on
詳細
ActiveRecordで、validation時にonを利用することで、
Modelの任意のアクション時のみValidationを実行することができます。
サンプル
テーブル定義
CREATE TABLE "articles" ( "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255), "text" text, "created_at" datetime, "updated_at" datetime );
Validation
class Article < ActiveRecord::Base has_many :comments, dependent: :destroy validates :title, length: { is: 5 }, on: :create end
試行
rails console(pry)で試行します。
新規作成時(最初にsaveするまで)はValidationが有効になっているが、
一度保存した後はValidationが無効になっていることがわかります。
[1] pry(main)> a = Article.new
=> #<Article id: nil, title: nil, text: nil, created_at: nil, updated_at: nil>
[2] pry(main)> a.title = 4
=> 4
[3] pry(main)> a.valid?
=> false
[4] pry(main)> a.errors.messages
=> {:title=>["is the wrong length (should be 5 characters)"]}
[5] pry(main)> a.title = '12345'
=> "12345"
[6] pry(main)> a.valid?
=> true
[7] pry(main)> a.save
(0.1ms) begin transaction
SQL (3.1ms) INSERT INTO "articles" ("created_at", "title", "updated_at") VALUES (?, ?, ?) [["created_at", "2014-07-02 23:53:51.377843"], ["title", "12345"], ["updated_at", "2014-07-02 23:53:51.377843"]]
(3.4ms) commit transaction
=> true
[8] pry(main)> a.title = 'invalid title'
=> "invalid title"
[9] pry(main)> a.valid?
=> true
[10] pry(main)> a.save
(0.1ms) begin transaction
SQL (1.9ms) UPDATE "articles" SET "title" = ?, "updated_at" = ? WHERE "articles"."id" = 22 [["title", "invalid title"], ["updated_at", "2014-07-02 23:54:49.783148"]]
(3.4ms) commit transaction
=> true