Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails 4:向现有表中添加多个列_Ruby On Rails_Ruby_Ruby On Rails 4 - Fatal编程技术网

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

Ruby on rails Rails 4:向现有表中添加多个列,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我知道如何向现有表中添加一列。现在,我必须向现有表中添加许多列。有没有较短的方法: add_col1_col2_col3_col4_.._coln_to_tables col1:integer col2:integer etc... 我是否必须为我必须添加的所有附加列执行上述操作?只需创建迁移并生成这些列,即: class ChangeTables < ActiveRecord::Migration def change change_table :tables do |t|

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

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

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

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

class ChangeTables < ActiveRecord::Migration
  def change
    change_table :tables do |t|
      100.times do |i|
        t.integer :"column_#{i}"
      end
    end
  end
end
类变更表
不需要。你能行

假设TableName是用户

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

此迁移文件可以在循环中完成。 但你真的想这么做吗?创建这样一个沉重的模型来保存所有内容看起来是不正确的。

这里有一个很好的资源,其中列出了可以用来操作数据库的所有命令。您也可以通过以下方式执行此任务:

rails g migration addmore columnstomodel

然后打开迁移文件并放置:

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

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

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

rails g migration add_first_column_and_second_column_to_model first_column:string second_column:string

用于创建带有
列的
新模型
表格
的命令:

rails g model ModelName col_name1:string col_name2:integer col_name3:text ...
用于在现有表下添加更多
列的命令:

rails g migration AddColumnToModelName col_name4:string col_name5:integer ...
最后,通过命令运行
migration

rake db:migrate

你能指定像整数数组这样的东西吗<代码>添加列:规程,:天,:整数,数组:真