Programing

Rails 마이그레이션을 사용하여 열을 삭제하는 방법

lottogame 2020. 10. 3. 09:48
반응형

Rails 마이그레이션을 사용하여 열을 삭제하는 방법


Rails 마이그레이션을 통해 데이터베이스 테이블 열을 삭제하는 구문은 무엇입니까?


remove_column :table_name, :column_name

예를 들면 :

remove_column :users, :hobby

사용자 테이블에서 취미 열을 제거합니다.


이전 버전의 Rails

ruby script/generate migration RemoveFieldNameFromTableName field_name:datatype

Rails 3 이상

rails generate migration RemoveFieldNameFromTableName field_name:datatype

Rails 4가 업데이트되었으므로 마이그레이션에서 change 메서드를 사용하여 열을 삭제하면 마이그레이션이 성공적으로 롤백됩니다. Rails 3 애플리케이션에 대한 다음 경고를 읽으십시오.

Rails 3 경고

이 명령을 사용할 때 다음 사항에 유의하십시오.

rails generate migration RemoveFieldNameFromTableName field_name:datatype

생성 된 마이그레이션은 다음과 같습니다.

  def up
    remove_column :table_name, :field_name
  end

  def down
    add_column :table_name, :field_name, :datatype
  end

데이터베이스 테이블에서 열을 제거 할 때 change 메서드를 사용하지 마십시오 (Rails 3 앱의 마이그레이션 파일에서 원하지 않는 예).

  def change
    remove_column :table_name, :field_name
  end

Rails 3의 변경 방법은 remove_column과 관련하여 현명하지 않으므로이 마이그레이션을 롤백 할 수 없습니다.


rails4 앱에서는 열을 제거하는 데에도 change 메서드를 사용할 수 있습니다. 세 번째 매개 변수는 data_type이며 선택 사항 인 네 번째 매개 변수에서 옵션을 제공 할 수 있습니다. 문서의 '사용 가능한 변환'섹션에 약간 숨겨져 있습니다 .

class RemoveFieldFromTableName < ActiveRecord::Migration
  def change
    remove_column :table_name, :field_name, :data_type, {}
  end
end

이를 수행하는 두 가지 좋은 방법이 있습니다.

remove_column

다음과 같이 간단히 remove_column을 사용할 수 있습니다.

remove_column :users, :first_name

스키마를 한 번만 변경해야하는 경우 괜찮습니다.

change_table 블록

다음과 같이 change_table 블록을 사용하여이 작업을 수행 할 수도 있습니다.

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

더 읽기 쉽기 때문에 이것을 선호하며 한 번에 여러 가지를 변경할 수 있습니다.

다음은 지원되는 change_table 메서드의 전체 목록입니다.

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


레일 5에서는 터미널에서 다음 명령을 사용할 수 있습니다.

rails generate migration remove_COLUMNNAME_from_TABLENAME COLUMNNAME:DATATYPE

for example to remove the column access_level(string) from table users:

rails generate migration remove_access_level_from_users access_level:string

and then run:

rake db:migrate

Remove Columns For RAILS 5 App

rails g migration Remove<Anything>From<TableName> [columnName:type]

Command above generate a migration file inside db/migrate directory. Snippet blow is one of remove column from table example generated by Rails generator,

class RemoveAgeFromUsers < ActiveRecord::Migration
  def up
    remove_column :users, :age
  end
  def down
    add_column :users, :age, :integer
  end
end

I also made a quick reference guide for Rails which can be found at here.


You can try the following:

remove_column :table_name, :column_name

(Official documentation)


rails g migration RemoveXColumnFromY column_name:data_type

X = column name
Y = table name

EDIT

Changed RemoveXColumnToY to RemoveXColumnFromY as per comments - provides more clarity for what the migration is actually doing.


Generate a migration to remove a column such that if it is migrated (rake db:migrate), it should drop the column. And it should add column back if this migration is rollbacked (rake db:rollback).

The syntax:

remove_column :table_name, :column_name, :type

Removes column, also adds column back if migration is rollbacked.

Example:

remove_column :users, :last_name, :string

Note: If you skip the data_type, the migration will remove the column successfully but if you rollback the migration it will throw an error.


Clear & Simple Instructions for Rails 5.2

WARNING: You will lose data if you remove a column from your database. To proceed, see below:


1. Create a migration

  • Run the following command in your terminal:

rails generate migration remove_fieldname_from_tablename fieldname:string

  • Note: the table name should be in plural form as per rails convention.

Example:

  • In my case I want to remove the accepted column (a boolean value) from the quotes table:

rails g migration RemoveAcceptedFromQuotes accepted:boolean

There is a special syntactic shortcut to generate migrations that add fields to a table.

rails generate migration add_fieldname_to_tablename fieldname:string

2. Check the migration

# db/migrate/20190122035000_remove_accepted_from_quotes.rb
class RemoveAcceptedFromQuotes < ActiveRecord::Migration[5.2]
  # with rails 5.2 you don't need to add a separate "up" and "down" method.
  def change
    remove_column :quotes, :accepted, :boolean
  end
end

3. Run the migration

rake db:migrate

....And then you're off to the races!


To remove the column from table you have to run following migration:

rails g migration remove_column_name_from_table_name column_name:data_type

Then run command:

rake db:migrate

Give below command it will add in migration file on its own

rails g migration RemoveColumnFromModel

After running above command you can check migration file remove_column code must be added there on its own

Then migrate the db

rake db:migrate

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


For removing column from table in just easy 3 steps as follows:

  1. write this command

rails g migration remove_column_from_table_name

after running this command in terminal one file created by this name and time stamp (remove_column from_table_name).

Then go to this file.

  1. inside file you have to write

    remove_column :table_name, :column_name

  2. Finally go to the console and then do

    rake db:migrate


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


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


Simply, You can remove column

remove_column :table_name, :column_name

For Example,

remove_column :posts, :comment

Heres one more from rails console

ActiveRecord::Migration.remove_column(:table_name, :column_name)

참고URL : https://stackoverflow.com/questions/2831059/how-to-drop-columns-using-rails-migration

반응형