[RUBY] Change the database (MySQL) primary key to any column.

at first…

It is the primary key (: id column) that is always created when a table is created in the database, but by default it is registered from the first in the order in which it was registered in the record. However, if you look at the existing services, you can see that the product number is included in the URL or the user information can be viewed on a page such as https://www.uniqlo.com/jp/ja/products/E428313-000. The user name may be a parameter. Therefore, in this post, I will introduce how to change the primary key to an arbitrary column in the database (MySQL).

How to change the database (MySQL) primary key to any column

db/migrate/_Migration file.rb


class ● ● ● < ActiveRecord::Migration[5.2]
  def change
    create_table :table name, id: false, primary_key: :Column name to be the primary key do|t|
      # `id: false`At this table`:id`Do not create columns. It is a description.
      # `primary_key:`Specify the column name to be the primary key in.
      t.timestamps
    end
  end
end

app/models/Model name.rb


class model name< ApplicationRecord
  self.primary_key = "Column name to be the primary key"
    #By making this description in the model file, the column that will be the primary key (primary key) is specified.
end

--By describing the column that is the primary key in the model file, you can use model name.find (params [: id]) from the controller to : id. When you call the record of ...

Server log


Parameters: {"id"=>"value"}
SELECT  `table name`.* FROM `table name` WHERE `table name`.`Column name as the primary key` =Value LIMIT 1`

And you can see that the value that was used as the primary key is read properly.

Recommended Posts

Change the database (MySQL) primary key to any column.
[Ruby on Rails] How to change the column name
[Rails] How to change the column name of the table
[Ruby on Rails] From MySQL construction to database change
How to dynamically change the column name acquired by MyBatis
When you want to change the MySQL password of docker-compose
Dynamically switch the database to connect to
Change DB from SQLite to MySQL
[Rails] How to create a table, add a column, and change the column type
Add foreign key to column with migrate
How to change the timezone on Ubuntu
Ransack sort_link How to change the color!
If you are using Android Room and want to change the column definition
Ask Sota to speak back the database values
Procedure to change lower_case_table_names = 1 in MySQL 8.0 of CentOS 8.3
Change the timezone of the https-portal container to JST
How to delete the database when recreating the application
How to generate a primary key using @GeneratedValue
[Java / PostgreSQL] Connect the WEB application to the database
http: // localhost: How to change the port number
DataSource connection from WebSphere to MySQL (DataSource property change?)