使用 RubyMine 在模型中添加/更新列 [英] Adding/Updating column in a Model using RubyMine

查看:77
本文介绍了使用 RubyMine 在模型中添加/更新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a web app that basically interacts with a db table through a form. Recently I had to make some changes which resulted in me adding another column to the db table. I'm using RubyMine for developing and can't figure out how to update the model so that it contains the new column. I've added it inside the model as so:

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 中添加了它:

I've also added it inside the 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).它只显示旧列:

Problem is when I run the rails console and look up my model object it doesn't show the new column that I have added (:is_active). It only shows the old columns:

>> 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)

我错过了什么?

推荐答案

你应该知道的是,删除所有更改你已经添加到模型 app/models/Student.rbdb/schema.rb

What you should do know, is to delete all changes you have added to model app/models/Student.rb and to db/schema.rb

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

Then you should go to your terminal/console and type

$ rails g migration add_column_name_to_student column_name:type

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

This command will create new file in db/migrate/ folder.

$ rake db:migrate

使用 rake db:migrate 更新数据库架构后.如果您想通过表单设置此值,请转到您的 app/models/Student.rb 并将新的 column_name 添加到 attr_accessible 中.

After updating your database schema with rake db:migrate. Go to your app/models/Student.rb and add new column_name into attr_accessible, if you want to setup this value by form.

整个过程与您的 IDE 无关.

This whole procedure has nothing to do with your IDE.

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

Here are some other resources, where you can get information how to add new column to models.

生成自动添加更改的 Rails 迁移Rails 3:如何向现有数据库表添加新字段

您绝对应该避免以您的方式添加新列.它很混乱,使您的代码难以维护.

You should definitely avoid adding new columns the way you did that. It's messy and makes your code difficult to maintain.

这篇关于使用 RubyMine 在模型中添加/更新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆