Search code examples
ruby-on-railspostgresqlruby-on-rails-5database-migrationrails-migrations

Rails - DB migration best practice


I have designed the following migration and wanted to check with the community is that is meeting the best practices of rails migration. I am running a postgres db.

I am trying to achieve a db structure where the various status attached to a user is stored in a separate table. for instance, its marital status.

let me know if that sounds like a reasonably efficient table design. and what I could improve.

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

end


Solution

  • In this case, best practices would dictate:

    1. Break each create_table into its own migration.
    2. Your table names should be pluralized, e.g. marital_statuses.
    3. Time stamps are a good idea.
    4. Consider adding indexes to fields that will be queried regularly, e.g. model names, user emails, or foreign keys.

    Check out the rails guide on migrations for information about best practice: https://edgeguides.rubyonrails.org/active_record_migrations.html