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).
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