Rails Rails 中给数据表添加字段,为什么没添加上?新手求助.

mayday · 2012年11月07日 · 最后由 mayday 回复于 2012年11月07日 · 9383 次阅读

按照教程添加的字段 '''rails g migration AddEmailToPeople email:string rake db:migrate'''

个人认为添加成功后 module 的内容应该会改变,但是 models/person.rb 中并未显示添加的字段,后面插入数据时也出错. 应该是没添加上字段 email,不知道哪里错了...

你的 db/migrate 目录下有没有 [timestamp]_add_email_to_people.rb 文件?内容是什么?

@blacktulip class AddEmailToPerson < ActiveRecord::Migration def change add_column :people, :email, :string end end

model 不会自己添加的,你 generate 的只是一个 migration,用来同步数据库结构的。model 需要自己添加。

class People attr_accessible :email

validates :email, :presence => true end

#2 楼 @mayday 看起来没问题。你用 rake g model 的时候,model 里面会自动添加 attr_accessible 的 attributes , 但是用 rake g migrate 的时候,rails 不会去动你的 model 的。需要自己手动添加。

#3 楼 @woaigithub 我是按照 web 开发敏捷之道上做的,上面添加字段后,只改了 View 部分。

有这么一句话:在开发模式下,每当浏览器请求时,rails 都会重新加载模型类,因此,模型类总是会体现当前的数据库结构。

#5 楼 @blacktulip 那我先试试手动改一下 model 的内容

书上或者 webpage 的人,很多时候没有考虑那么多,只写出来一些关键的地方,其他的有可能没有提到,很多时候需要我们自己参悟,习惯就好了,面面俱到,那一辈子也写不完书了。

#6 楼 @mayday 请问这是在那一章哪一节说的啊?我只看到有这么一段

It turns out that the Rails dispatcher is pretty clever. In development mode (as opposed to testing or production), it automatically reloads application source files when a new request comes along. That way, when we edit our application, the dispatcher makes sure it’s running the most recent changes. This is great for development.

我会先把名字改成一致。

#8 楼 @woaigithub #9 楼 @blacktulip

恩,需要自己手动在 model 中添加字段,已成功,谢谢两位了。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号