Specify user primary key in migration

I have a data structure:

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

The user ID must be the primary key (the name is not important, it can default to :id ). However, I do not want it to automatically increase or something else, just take the provided value and write it to the database.

How do I customize migration and model to achieve what I want?

+3
source share
2 answers
  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 the model:

  set_primary_key :userID 
+18
source

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

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

to check it out.

0
source

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


All Articles