Tbpgr Blog

元エンジニア 人事 tbpgr(てぃーびー) のブログ

Ruby on Rails | Validation | uniqueness

概要

uniqueness

詳細

ActiveRecordで、validation時にuniquenessを利用することで、
値が一意であることをチェックします。

サンプル

テーブル定義
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, uniqueness: true
end
試行

rails console(pry)で試行します。

[1] pry(main)> a = Article.new
=> #<Article id: nil, title: nil, text: nil, created_at: nil, updated_at: nil>
[2] pry(main)> a.title = 'hoge'
=> "hoge"
[3] pry(main)> a.valid?
  Article Exists (0.8ms)  SELECT  1 AS one FROM "articles"  WHERE "articles"."title" = 'hoge' LIMIT 1
=> true
[4] pry(main)> a.save
   (0.1ms)  begin transaction
  Article Exists (0.7ms)  SELECT  1 AS one FROM "articles"  WHERE "articles"."title" = 'hoge' LIMIT 1
  SQL (1.9ms)  INSERT INTO "articles" ("created_at", "title", "updated_at") VALUES (?, ?, ?)  [["created_at", "2014-07-02 23:46:56.003475"], ["title", "hoge"], ["updated_at", "2014-07-02 23:46:56.003475"]]
   (2.7ms)  commit transaction
=> true
[5] pry(main)> b = Article.new
=> #<Article id: nil, title: nil, text: nil, created_at: nil, updated_at: nil>
[6] pry(main)> b.title = 'hoge'
=> "hoge"
[7] pry(main)> b.valid?
  Article Exists (0.7ms)  SELECT  1 AS one FROM "articles"  WHERE "articles"."title" = 'hoge' LIMIT 1
=> false
[8] pry(main)> b.errors.message
NoMethodError: undefined method `message' for #<ActiveModel::Errors:0x007f7a693b45d0>
from (pry):10:in `__pry__'
[9] pry(main)> b.errors.messages
=> {:title=>["has already been taken"]}