如何在Rails迁移的change_table中可逆地移除列?
Rails change_table 中实现可逆移除列的正确方式
在Rails的change迁移中,直接使用add_column和remove_column并指定类型参数时,迁移是支持可逆的:
add_column :widgets, :color, :string remove_column :widgets, :flavor, :string
但在change_table块内使用t.remove时,这个方法仅接受列名列表,如果你传入类型参数,它会被当作列名处理,导致错误:
change_table(:widgets) do |t| t.column :color, :string t.remove :flavor, :string # 错误!这里会尝试移除名为"string"的列 end
执行时会抛出错误:
remove_columns is only reversible if given a type.
要在change_table中实现可逆的列移除,你可以使用**t.remove_columns(复数形式)**,它支持传入列名和对应的类型参数,这样Rails就能生成可逆的迁移逻辑:
def change change_table(:widgets) do |t| t.column :color, :string t.remove_columns :flavor, :string end end
另外,你也可以选择将remove_column单独放在change_table块外,保持原有可逆写法:
def change change_table(:widgets) do |t| t.column :color, :string end remove_column :widgets, :flavor, :string end
内容的提问来源于stack exchange,提问作者Grant Birchmeier
相关产品推荐
相关产品推荐

