Kamipo_normal

ActiveRecordでunsigned型をサポートしてないのが気になる Edit

  • Kamipo_normal kamipo posted in (Edited )
  • rosylilly
  • Vit-Symty@github
  • arihh
  • matsubo@github
  • yoppi@github
  • cutmail
  • takehiro0740
  • yaotti
Edit

MySQLのほうから来た人だとidみたいなシーケンス値やhoge_countみたいなカウント保持するカラムはunsigned intで定義するのが普通な気がするのですが、ActiveRecord::Migrationではunsignedをサポートしていません。
かるく調べた限りだと、unsignedをサポートしてるのってMySQLぐらいらしく、PostgreSQLはサポートしてないしSQLite3はスキーマ定義のときにunsignedって書いてもエラーにならないけど完全に無視されてて余裕でマイナスの値を保持できてしまう。
そういう背景があってunsignedを扱いたいという要件はActiveRecordやRailsにおいてはエッジケースだという見解らしく、当面ActiveRecordでunsignedがサポートされる見込みはないのかもしれません。
そこで、activerecord-unsigned-columnというActiveRecord::Migrationでunsigned型を扱えるやつを作りました。

Gemfile
gem 'activerecord-unsigned-column', :git => 'git://github.com/kamipo/activerecord-unsigned-column.git'

こうやってGemfileに書いてbundle installしてrake db:migrateすると

db/migrate/20121009024024_create_tweets.rb
class CreateTweets < ActiveRecord::Migration
  def change
    create_table :tweets do |t|
      t.references :user
      t.string :text
      t.unsigned :retweets_count, :default => 0
      t.unsigned :favorites_count, :default => 0

      t.timestamps
    end
    add_index :tweets, :user_id
  end
end
CREATE TABLE `tweets` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(10) unsigned DEFAULT NULL,
  `text` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `retweets_count` int(10) unsigned DEFAULT '0',
  `favorites_count` int(10) unsigned DEFAULT '0',
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

いい感じにunsignedが扱えます!これでMySQLの人も安心ですね!


Version Information


Sign up and follow kamipo :)

Sign up with GitHub/Twitter

x close