Generate a model with a string field as a primary key

I want to create a User model inside my Ruby on Rails application.

I use the following command:

 rails generate model User email:string name:string role:string 

Can email be defined as a primary key with this command? Or should I modify the database migration file that I create with this command? And How?

+5
source share
2 answers

No, you can’t. By default, the primary key is an auto-incrementing integer.

However, you can open the migration that was generated from this command and modify 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 that you can pass two options. In particular, you need to set :id to false so as not to 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| 
+7
source

To add @Simone Carletti to the answer, you may need to execute to set the primary key (if it is unclear). This would be especially true if you are modifying an existing table that you are clearly 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 in some of our applications and what we need ( primary_key: :uuid does not work) ...

enter image description here


+5
source

Source: https://habr.com/ru/post/1239635/


All Articles