【问题标题】:adding multipe new columns in rails migration using block使用块在 Rails 迁移中添加多个新列
【发布时间】:2018-11-06 07:52:52
【问题描述】:

有没有比这种方式更好的向rails表添加新列的方法

class AddColumnsToUsers < ActiveRecord::Migration[5.1]
  def change
    add_column :users, :first_name, :string
    add_column :users, :last_name, :string
    add_column :users, :contact1, :integer
    add_column :users, :contact2, :integer
    add_column :users, :contact3, :decimal
    add_column :users, :contact4, :integer
    add_column :users, :contact5, :integer
    add_column :users, :contact6, :string
    add_column :users, :contact7, :integer
    add_column :users, :contact8, :integer
    add_column :users, :contact9, :integer
  end
end

我们可以使用 change_table 方法并将这些写在一个块中吗?而不是一次又一次地重复 add_column

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 migration ruby-on-rails-5


    【解决方案1】:

    您可以像这样将多个列添加到同一个表中

    def change
      change_table :users do |t|
        t.string :first_name
        t.string :last_name
      end
    end
    

    【讨论】:

      【解决方案2】:

      如果你只是想晒干,也可以这样写,

      {
        string: [:first_name, :last_name, :contact6],
        integer: [:contact1 ,:contact2 ,:contact4 ,:contact5 ,:contact7 ,:contact8 ,:contact9],
        decimal: [:contact3] 
      }.each do |type, columns| 
        columns.each { |col| add_column :users, col, type }
      end
      

      【讨论】:

      • 我会坚持 OP 编写迁移的方式或使用 Sumanth Madishetty 的建议。我不建议您在迁移中过于聪明。
      猜你喜欢
      • 1970-01-01
      • 2014-12-25
      • 2011-10-09
      • 2017-02-17
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      相关资源
      最近更新 更多