使用RubyMine在模型中添加/更新列

时间:2013-07-18 15:47:15

标签: ruby-on-rails ruby ruby-on-rails-3 rubymine

我正在开发一个基本上通过表单与db表交互的Web应用程序。最近我不得不进行一些更改,这导致我在db表中添加了另一列。我正在使用RubyMine进行开发,无法弄清楚如何更新模型以使其包含新列。我已将其添加到模型中,如下所示:

class Student < ActiveRecord::Base
attr_accessible :f_name, :floor_pref, :l_name, :is_active

validates_presence_of :f_name, :floor_pref, :l_name
end

我还在schema.rb中添加了它:

ActiveRecord::Schema.define(:version => 20130620140537) do

create_table "students", :force => true do |t|
t.string   "f_name"
t.string   "l_name"
t.string   "floor_pref"
t.boolean "is_active"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end

end

并且也在迁移内部如此:

class CreateStudents < ActiveRecord::Migration
def change
create_table :students do |t|
  t.string :f_name
  t.string :l_name
  t.string :floor_pref
  t.boolean :is_active

  t.timestamps
end
end
end

问题是当我运行rails控制台并查找我的模型对象时,它没有显示我添加的新列(:is_active)。它只显示旧列:

>> Student
Loading development environment (Rails 3.2.13)
Switch to inspect mode.
Student(id: integer, f_name: string, l_name: string, floor_pref: string, created_at:    datetime, updated_at: datetime)

我错过了什么?

3 个答案:

答案 0 :(得分:5)

您应该知道的是删除已添加到模型 app / models / Student.rb 的所有更改以及 db / schema.rb

然后你应该去你的终端/控制台并输入

$ rails g migration add_column_name_to_student column_name:type

此命令将在db / migrate /文件夹中创建新文件。

$ rake db:migrate

使用rake db:migrate更新数据库模式后。如果要按表单设置此值,请转到app / models / Student.rb并将新column_name添加到 attr_accessible

整个过程与您的IDE无关。

以下是一些其他资源,您可以从中获取有关如何向模型添加新列的信息。

Generate Rails Migrations That Automagically Add Your Change Rails 3: How to add a new field to an existing database table

你绝对应该避免像你那样添加新列。它很乱,使你的代码难以维护。

答案 1 :(得分:1)

这不是向表中添加新列的正确方法。您希望打开控制台并运行以下命令:rails g migration add_column_name_to_table column_name:type之后运行捆绑执行rake rake db:migrate。把东西推进去并不好。

答案 2 :(得分:0)

例如:如果我想将postedon列添加到posts表,那么:

rails g migration AddPostedOnToPosts  posted_on:date

这将自动在您的迁移文件中添加列。