【问题标题】:Rails - DB migration best practiceRails - 数据库迁移最佳实践
【发布时间】:2023-03-19 23:06:02
【问题描述】:

我设计了以下迁移,并想与社区确认是否符合 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-rails postgresql ruby-on-rails-5 database-migration rails-migrations


    【解决方案1】:

    在这种情况下,最佳实践将规定:

    1. 将每个create_table 拆分为自己的迁移。
    2. 您的表名应该是复数形式,例如marital_statuses
    3. 时间戳是个好主意。
    4. 考虑将索引添加到将定期查询的字段,例如型号名称、用户电子邮件或外键。

    查看有关迁移的 Rails 指南以获取有关最佳实践的信息:https://edgeguides.rubyonrails.org/active_record_migrations.html

    【讨论】:

      【解决方案2】:

      让我们开始吧:

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

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

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

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

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

      【讨论】:

      • 感谢您的洞察力。我将其作为多个模型运行。我注意到时间戳 null:false 是由 rails 添加的(我正在运行(5.2.2)所以我什么也没做,只是检查了它的存在。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      • 2019-01-01
      • 1970-01-01
      • 2023-03-25
      • 2010-11-02
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多