【问题标题】:rails migration : check existence of multiple columnsrails迁移:检查是否存在多个列
【发布时间】:2023-04-10 17:06:01
【问题描述】:

我有一个公司表,我想检查是否存在多个列以删除它们。

class RemoveSettingsReportColumnsFromCompany < ActiveRecord::Migration[5.1]
  def change
    if column_exists?( :companies, :automatically_send_report ) && column_exists?( :companies, :time_limit_for_sending_report ) && column_exists?( :companies, :report_fragment_color ) && column_exists?( :companies, :display_default_avatar )
      remove_column :companies, :automatically_send_report, :boolean
      remove_column :companies, :time_limit_for_sending_report, :integer
      remove_column :companies, :report_fragment_color, :string
      remove_column :companies, :display_default_avatar, :boolean
    end
  end
end

正如您所见,函数 column_exists 的使用存在冗余,我想更好地组织和减少我的代码,有人可以告诉我是否有使用 column_exists 的方法 以其他方式,并将其作为我要删除的所有列的参数?

【问题讨论】:

    标签: ruby-on-rails ruby database migration


    【解决方案1】:

    可以稍微简化一下。首先 - 您可以使用Company.attribute_names 列出所有属性。它将返回一个数组。所以你可以这样做:

    if (%w[automatically_send_report time_limit_for_sending_report report_fragment_color display_default_avatar] - Company.attribute_names).empty?
      # migration code
    end
    

    另一个更漂亮一点的解决方案(IMO)是:

    if Company.attribute_names.to_set.superset?(Set['automatically_send_report', 'time_limit_for_sending_report', 'report_fragment_color', 'display_default_avatar'])
      # migration code
    end
    

    【讨论】:

      【解决方案2】:
      FIELDS = %i[automatically_send_report time_limit_for_sending_report
                  report_fragment_color display_default_avatar].zip(
               %i[boolean integer string boolean]).to_h
      
      def up
        FIELDS.keys.each do |col|
          remove_column(:companies, col) if column_exists?(:companies, col)
        end
      end
      
      def down
        FIELDS.each do |col, type|
          add_column(:companies, col, type) unless column_exists?(:companies, col)
        end
      end
      

      【讨论】:

      • 感谢您的快速回复 Aleksei,但您忘记输入列类型!你能再看一遍吗?
      • remove_column 不需要类型,即使给定了也会被有效地忽略。
      • 啊哈,我明白了,但只是一个问题:当我想要回滚时不需要吗?
      • 我不知道change 是如何处理这个问题的。为了清楚起见,我通常使用up 和down。更新了答案。
      猜你喜欢
      • 2019-07-05
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      • 2010-12-11
      • 1970-01-01
      • 2010-12-23
      相关资源
      最近更新 更多