How to drop columns using Rails migration

2019-01-20 20:56发布

What's the syntax for dropping a database table column through a Rails migration?

17条回答
唯我独甜
2楼-- · 2019-01-20 21:23

In a rails4 app it is possible to use the change method also for removing columns. The third param is the data_type and in the optional forth you can give options. It is a bit hidden in the section 'Available transformations' on the documentation .

class RemoveFieldFromTableName < ActiveRecord::Migration
  def change
    remove_column :table_name, :field_name, :data_type, {}
  end
end
查看更多
聊天终结者
3楼-- · 2019-01-20 21:23

There are two good ways to do this:

remove_column

You can simply use remove_column, like so:

remove_column :users, :first_name

This is fine if you only need to make a single change to your schema.

change_table block

You can also do this using a change_table block, like so:

change_table :users do |t|
  t.remove :first_name
end

I prefer this as I find it more legible, and you can make several changes at once.

Here's the full list of supported change_table methods:

http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_table

查看更多
姐就是有狂的资本
4楼-- · 2019-01-20 21:24
remove_column :table_name, :column_name

For instance:

remove_column :users, :hobby

would remove the hobby Column from the users table.

查看更多
The star\"
5楼-- · 2019-01-20 21:27

Do like this;

rails g migration RemoveColumnNameFromTables column_name:type

I.e. rails g migration RemoveTitleFromPosts title:string

Anyway, Would be better to consider about downtime as well since the ActiveRecord caches database columns at runtime so if you drop a column, it might cause exceptions until your app reboots.

Ref: Strong migration

查看更多
虎瘦雄心在
6楼-- · 2019-01-20 21:32

Through
remove_column :table_name, :column_name
in a migration file

You can remove a column directly in a rails console by typing:
ActiveRecord::Base.remove_column :table_name, :column_name

查看更多
干净又极端
7楼-- · 2019-01-20 21:37

remove_column in change method will help you to delete the column from the table.

class RemoveColumn < ActiveRecord::Migration
  def change
    remove_column :table_name, :column_name, :data_type
  end
end

Go on this link for complete reference : http://guides.rubyonrails.org/active_record_migrations.html

查看更多
登录 后发表回答