Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate a model with a string field as primary key

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?

like image 373
Jepessen Avatar asked Jan 01 '16 19:01

Jepessen


People also ask

Can we use string data type as primary keys?

The short answer : It's perfectly fine to use a string as a primary key.

What is best way to create primary key as a string field instead of integer in rails?

So: use :id => false so as not to generate an integer primary key. use the desired datatype, and add :null => false.


1 Answers

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|
like image 126
Simone Carletti Avatar answered Oct 11 '22 23:10

Simone Carletti