假设我在Rails迁移中创建了一个表,指定省略ID列:
create_table :categories_posts, :id => false do |t|
t.column :category_id, :integer, :null => false
t.column :post_id, :integer, :null => false
end
后来我决定将ID列添加为主键,因此我创建了一个新的迁移:
class ChangeCategoriesToRichJoin < ActiveRecord::Migration
def self.up
add_column :categories_posts, :id, :primary_key
end
def self.down
remove_column :categories_posts, :id
end
end
但是当我迁移后查看表格时,它看起来像这样:
category_id
post_id
id
id列位于表的最后位置,而通常id列是第一个。
有没有办法将ChangeCategoriesToRichJoin迁移更改为坚持在表格中的category_id列之前创建的id列?
或者我是否需要删除表并在“创建表”定义中添加列?
答案 0 :(得分:5)
使用:after => :another_column_name
,例如:
change_table :users do |t|
t.integer :like_count, :default => 0, :after => :view_count
end
答案 1 :(得分:2)
另请参阅此问题,并提供可能的解决方案: In a Rails Migration (MySQL), can you specify what position a new column should be?
答案 2 :(得分:1)
我自己无法按顺序放置列,但是使用Rails可以回滚,更改旧的迁移文件以按照您想要的顺序添加新列,然后重新迁移旧的迁移,包括新领域。它并不完全理想,但能够轻松迁移和回滚,如果您的OCD足以要求列顺序,它可以工作。 :P
我不是专家,但我已经阅读了很多Rails文档(以及最近的文档),并且无法回想起为此找到解决方案。