【问题标题】:Is it possible to DRY this migration up?是否有可能干燥这种迁移?
【发布时间】:2012-02-03 10:10:15
【问题描述】:

我有一个表,我想要一些其他表引用的文件夹,到目前为止,我的迁移脚本如下所示:

create_table :folders do |t|
  t.timestamps
end

....

change_table table1 do |t|
  t.references :folders
end
change_table table2 do |t|
  t.references :folders
end
change_table table3 do |t|
  t.references :folders
end
change_table table4 do |t|
  t.references :folders
end

由于我对每个表都做基本相同的事情,有没有更简洁和可维护的方式来编写这个?

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby activerecord migration dry


    【解决方案1】:

    尝试这样做:

    [table1, table2, table3, table4].each do |tbl|
        change_table tbl { |t| t.references :folders }
    end
    

    我希望你不要用table{#n} 模式命名表,并在你的实际代码中给它们起好名字:)

    【讨论】:

    • 是的,这些名字只是为了抽象例子:)
    【解决方案2】:

    你能不能试试这个。

      (1..4).each do |num|
          change_table "table#{num}" do |t|
          t.references :folders
          end
        end
    

    希望它会有所帮助。

    【讨论】:

    • 你需要评估那个字符串,否则它只是一个字符串;它不是指向 table# 对象的东西。
    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多