首页 > 解决方案 > Rails - 数据库迁移最佳实践

问题描述

我设计了以下迁移,并想与社区确认是否符合 Rails 迁移的最佳实践。我正在运行一个 postgres 数据库。

我正在尝试实现一个数据库结构,其中附加到用户的各种状态存储在一个单独的表中。例如,它的婚姻状况。

让我知道这听起来是否像一个相当有效的桌子设计。以及我可以改进的地方。

class CreatePrequalifications < ActiveRecord::Migration[5.2]
 def change
   create_table :prequalifications do |t|
    t.string :attachment
    t.text :description
    t.integer :marital_status
    t.integer :professional_status
    t.integer :collateral_status
    t.integer :income_direct
    t.integer :income_support
    t.integer :income_scolarship
    t.integer :income_other
    t.boolean :blacklist

    t.references :user, foreign_key: true

    t.timestamps
  end
end

create_table :marital_status do |t|
  t.string :single
  t.string :married
  t.string :other
  t.string :divorced
  t.string :with_dependants
  t.references :user, foreign_key: true
  t.references :prequalifications, foreign_key: true
end

create_table :professional_status do |t|
  t.string :self_employed
  t.string :employed
  t.string :student
  t.string :other
  t.text :description
  t.datetime :contract_created_at
  t.datetime :contract_terminated_at

  t.references :user, foreign_key: true
  t.references :prequalifications, foreign_key: true
end

create_table :collateral_status do |t|
  t.string :collateral_name

  t.string :collateral_income
  t.boolean :visale_collateral
  t.boolean :student_collateral
  t.boolean :bank_collateral

  t.references :user, foreign_key: true
  t.references :prequalifications, foreign_key: true
end

结尾

标签: ruby-on-railspostgresqlruby-on-rails-5database-migrationrails-migrations

解决方案


让我们从:

  1. 是单次迁移吗?如果是这样,我会先将其拆分为多个迁移(每个表一个)。

  2. 为每个表添加时间戳 ( t.timestamps null: false)。你以后会感谢我的;)

  3. 对于状态表 ( martial_status, professional_status),只需使用名称和引用创建更简单的表(无需为每个值创建列)。此外,您可能不需要婚姻状况表,因为您可以使用classy_enum代替。

  4. prequalifications你有关系的整数列(maritial_statusprofessional_status)。不要那样做,使用references.

  5. 对于布尔列,定义默认值。


推荐阅读