Ruby-on-rails Rails 4:向现有表添加多列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28836153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:06:01  来源:igfitidea点击:

Rails 4: Add Multiple Columns to Existing Table

ruby-on-railsrubyruby-on-rails-4

提问by Sylar

I know how to add one column to an existing table. Now I have to add many columns to an existing table. Is there a shorter way for:

我知道如何向现有表中添加一列。现在我必须向现有表中添加许多列。是否有更短的方法:

add_col1_col2_col3_col4_.._coln_to_tables col1:integer col2:integer etc...

Do I have to do the above for ALL the additional columns I have to add?

我是否必须为我必须添加的所有附加列执行上述操作?

回答by Shweta

No not necessary. You can do

没有没有必要。你可以做

Assuming TableName is user

假设表名是用户

rails g migration AddColumnsToUser col1:integer col2:integer .. etc.

回答by Proto

Here's a good resource on ActiveRecord:Migrationswhich lists all the commands you can use to manipulate your databases. You can also do the task this way:

这是ActiveRecord:Migrations上的一个很好的资源,其中列出了可用于操作数据库的所有命令。您也可以通过以下方式完成任务:

rails g migration AddMoreColumnsToModel

rails g migration AddMoreColumnsToModel

Then open the migration file and put:

然后打开迁移文件并输入:

def change
  add_column :table, :new_column, :type
  # add as many columns as you need 
end

If you wanted to do what Maxd suggests, having literally 100 columns of the same type auto-create, his code is a good idea.

如果您想按照 Maxd 的建议进行操作,即自动创建 100 列相同类型的列,那么他的代码是一个好主意。

回答by Maxim

Just create migration and generate these columns i.e.:

只需创建迁移并生成这些列,即:

class ChangeTables < ActiveRecord::Migration
  def change
    change_table :tables do |t|
      100.times do |i|
        t.integer :"column_#{i}"
      end
    end
  end
end

回答by Dinesh Pallapa

Similar to above answers but for understanding purpose hope below naming convention is good.

类似于上面的答案,但为了理解目的,希望下面的命名约定是好的。

rails g migration add_first_column_and_second_column_to_model first_column:string second_column:string

回答by IcyBright

This migration file can be done in a loop. But do you really want to do this? It does not look correct to create such a heavy model to hold everything.

这个迁移文件可以循环完成。但你真的想这样做吗?创建如此沉重的模型来容纳所有东西看起来并不正确。

回答by puneet18

command to create new modeland tablewith columns:

创建new modeltable使用命令columns

rails g model ModelName col_name1:string col_name2:integer col_name3:text ...

command to add more columnsunder existing table:

命令columns在现有表下添加更多:

rails g migration AddColumnToModelName col_name4:string col_name5:integer ...

At last, run migrationby command:

最后,migration通过命令运行:

rake db:migrate