generate a model with a string field as primary key
No, you can't. By default the primary key is an auto-increment integer.
However, you can open the migration that was generated from the command, and change it (before running the rake db:migrate
command). The migration will likely have a create_table
command:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
# ...
end
end
end
If you read the create_table
documentation, you will notice you can pass two options. Specifically, you need to set :id
to false
to not generate an id
field, and you will need to specify the name of the primary key field.
create_table :users, id: false, primary_key: :email do |t|
To add to @Simone Carletti
's answer, you may need to use execute
to set the primary key
(if it's obscure). This would be especially true if you're modifying an existing table, which you're obviously not doing:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users, id: false do |t|
t.string :email, null: false
t.timestamps
end
execute "ALTER TABLE users ADD PRIMARY KEY (email);"
end
end
We use uuid
's in some of our apps, and that's what we had to do (primary_key: :uuid
didn't work)...