LoginSignup
3
5

More than 3 years have passed since last update.

【Rails】id以外の値を主キーに設定して、他のテーブルから参照する

Last updated at Posted at 2020-01-15

やりたいこと

・usersテーブルの主キーにuser_noを設定(idというフィールドは使わない)
・billsテーブルにuser_noを設定する
・userモデルとbillモデルを1対多の関係で紐付ける

既存の(他の人が作った)システムと連動する必要があったので、、、

実装

user

app/model/user.rb
class Customer < ApplicationRecord
  has_many :bills
usersテーブルのmigrationファイル
class CreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users, primary_key: :user_no, autoincrement: false do |t|
      t.string :name
      t.string :email
      t.timestamps
    end
  end
end

bill

app/model/bill.rb
class Bill < ApplicationRecord
  belongs_to :user
end
billsテーブルのmigrationファイル
class RegenerateBills < ActiveRecord::Migration[5.2]
  def change
    create_table :bills do |t|
      t.references :user #外部キー
      t.string :item_name
      t.integer :amount
      t.integer :total
      t.timestamps
    end
  end
end
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5