将列添加到rails表

时间:2014-04-22 05:27:38

标签: ruby-on-rails database-migration

我正在运行rails 1.9.3,我想在已迁移的表中添加一列。我尝试了以下内容:

首先,我刚刚编辑了迁移文件并添加了我的字段并运行rake db:migrate命令只是为了看到以下错误:

NameError: undefined local variable or method `migrate' for main:Object
from (irb):13
from /Users/praveenmody/.rvm/gems/ruby-1.9.3-p448/gems/railties-4.0.0/lib/rails/commands/console.rb:90:in `start'
from /Users/praveenmody/.rvm/gems/ruby-1.9.3-p448/gems/railties-4.0.0/lib/rails/commands/console.rb:9:in `start'
from /Users/praveenmody/.rvm/gems/ruby-1.9.3-p448/gems/railties-4.0.0/lib/rails/commands.rb:64:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'

接下来,我尝试从rails控制台运行以下命令:

rails generate migration add_place_to_coordinates place:string 

仅收到以下错误:

NameError: undefined local variable or method `string' for main:Object
from (irb):10
from /Users/praveenmody/.rvm/gems/ruby-1.9.3-p448/gems/railties-4.0.0/lib/rails/commands/console.rb:90:in `start'
from /Users/praveenmody/.rvm/gems/ruby-1.9.3-p448/gems/railties-4.0.0/lib/rails/commands/console.rb:9:in `start'
from /Users/praveenmody/.rvm/gems/ruby-1.9.3-p448/gems/railties-4.0.0/lib/rails/commands.rb:64:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'

这是我的迁移文件:

class CreateCoordinates < ActiveRecord::Migration
def change
create_table :coordinates do |t|
  t.float :lattitude
  t.float :longitude

  t.timestamps
end
end
end

2 个答案:

答案 0 :(得分:4)

不要在rails控制台中运行该命令。从项目目录中的普通shell运行它。

答案 1 :(得分:2)

回答有点晚,希望它有助于其他人:

rails生成迁移add_price_to_service_elements价格:十进制

其次是: rails db:migrate

说明: &#39;添加&#39; 用于添加列,&#39;价格&#39; 是要添加&#39;到&的列#39; 引用了&#39; service_elements&#39; 的表名。如果您将文字添加到由&#39; _&#39; (下划线)分隔的引号中,您将获得上述命令。 price:decimal进一步指定列将存储的值类型十进制值。

rake db:migrate 命令检查最新的迁移版本(在schema_migrations表中维护),在这种情况下执行上述命令生成的迁移版本。

正如已经指出的那样,这个命令需要从控制台和app目录中运行。

更新:为了使其正常运行,需要手动更新文件以更改以反映在浏览器上: 例如。控制器,视图(索引,显示,_形式等)