Rails migration for change column

后端 未结 9 989
一个人的身影
一个人的身影 2020-11-28 17:24

We have script/generate migration add_fieldname_to_tablename fieldname:datatype syntax for adding new columns to a model.

On the same line, do we have a

相关标签:
9条回答
  • 2020-11-28 18:15

    You can also use a block if you have multiple columns to change within a table.

    Example:

    change_table :table_name do |t|
      t.change :column_name, :column_type, {options}
    end
    

    See the API documentation on the Table class for more details.

    0 讨论(0)
  • 2020-11-28 18:18

    As I found by the previous answers, three steps are needed to change the type of a column:

    Step 1:

    Generate a new migration file using this code:

    rails g migration sample_name_change_column_type
    

    Step 2:

    Go to /db/migrate folder and edit the migration file you made. There are two different solutions.

    1. def change
          change_column(:table_name, :column_name, :new_type)
      end
      

    2.

        def up
            change_column :table_name, :column_name, :new_type
        end
    
        def down
            change_column :table_name, :column_name, :old_type
        end
    

    Step 3:

    Don't forget to do this command:

    rake db:migrate
    

    I have tested this solution for Rails 4 and it works well.

    0 讨论(0)
  • 2020-11-28 18:20

    To complete answers in case of editing default value :

    In your rails console :

    rails g migration MigrationName
    

    In the migration :

      def change
        change_column :tables, :field_name, :field_type, default: value
      end
    

    Will look like :

      def change
        change_column :members, :approved, :boolean, default: true
      end
    
    0 讨论(0)
提交回复
热议问题