开发者

Specify custom primary key in migration

开发者 https://www.devze.com 2023-03-14 09:33 出处:网络
I have a data structure: t.integer :userID t.string :apikey t.integer :characterID The userID should be the primary key (name is not important, it can default to :id). However, I don\'t want it to

I have a data structure:

  t.integer :userID
  t.string :apikey
  t.integer :characterID

The userID should be the primary key (name is not important, it can default to :id). However, I don't want it to be auto incrementing or anything else, just take the value provided and write it into the database.

How do I have to adjust开发者_运维技巧 the migration and the model to achieve what I want?


 create_table(:my_table, :primary_key => 'userID') do |t|
   # Primary key column will be created automatically
   # Do not create here
   # t.column :userID, :integer, :null => false
   ...
 end

Or

create_table :my_table, {:id => false} do |t|
  t.integer :userID
  t.string :apikey
  t.integer :characterID
  t.timestamps
 end
 execute "ALTER TABLE my_table ADD PRIMARY KEY (userID);"

And don't forget to put this line somewhere in model:

 set_primary_key :userID


Instead of circumventing the ActiveRecord model, I made userID a normal column and used

validates_uniqueness_of :userID, :message => "userID needs to be unique"

on the model to validate it.

0

精彩评论

暂无评论...
验证码 换一张
取 消