I want to create a User
model inside my Ruby on Rails application.
I use following command:
rails generate model User email:string name:string role:string
It is possible to define the email
as primary key with this command? Or I must modify the database migration file that I create with this command? And how?
The short answer : It's perfectly fine to use a string as a primary key.
So: use :id => false so as not to generate an integer primary key. use the desired datatype, and add :null => false.
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|
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With