我想添加一个新列:
class AddNameToUsers < ActiveRecord::Migration
def change
add_column :users, :name, :string, :first => true
end
end
我包含了参数:first
,以便将列放在所有其他列的前面。但似乎没有用:
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :default => "", :null => false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "name"
end
我做错了吗?
答案 0 :(得分:2)
我们无法使用迁移文件实现此目的。但我们可以做以下事情......
ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do
def add_column_options!(sql, options)
super
if options[:after]
sql << " AFTER #{quote_column_name(options[:after])}"
elsif options[:first]
sql << " FIRST"
end
end
end
So now
a.add_column :users, :name, :string, :after => "baz"
will execute
ALTER TABLE `users` ADD `name` varchar(20) AFTER `baz`
and
a.add_column :users, :name, :string, :first => true
will execute
ALTER TABLE `users` ADD `name` varchar(20) FIRST
Likewise for change_column.