LoginSignup
45
41

More than 5 years have passed since last update.

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

Last updated at Posted at 2012-12-26

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の人も安心ですね!

45
41
1

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
45
41