ALTER TABLE `ruby`.`item` CHANGE COLUMN `id` `item_id` INTEGER UNSIGNED NOT NULL DEFAULT 0,
DROP PRIMARY KEY,
ADD PRIMARY KEY USING BTREE(`item_id`);
/models/item.rbの内容を以下のように書き換えます。
(変更前)
class Item < ActiveRecord::Base
end
↓
(変更後)
class Item < ActiveRecord::Base
set_primary_key "item_id" #PK列名を変更します。
def before_create #insert実行直前に自動的に呼ばれます。
self.id = self.item_id_next
end
def item_id_next #自前で一意キーを取得します。
return ActiveRecord::Base.connection.select_value('select ifnull(max(item_id),0)+1 from item')
#ifnullを追加(2007/09/11),1レコード目のsaveでエラーになるため end
end
※before_create中の代入式の左辺の変数名は、PK列名に関わらず"id"になります。(う〜ん、これってPKが複合キーの場合はどうなるんだろう?)