ruby on rails:如何将数据库更改带到模型

时间:2013-02-07 22:47:29

标签: ruby ruby-on-rails-3

我在db / migrate下有更新迁移脚本,我做了

rake db:migrate

更新前的数据库脚本

class CreateStudents < ActiveRecord::Migration
  def change
    create_table :students do |t|
      t.string :firstname
      t.string :lastname      
      t.string :account
      t.timestamps
    end
  end
end 

更新后的数据库脚本

class CreateStudents < ActiveRecord::Migration
  def change
    create_table :students do |t|
      t.string :firstname
      t.string :lastname      
      t.string :account
      t.string :address      
      t.string :city
      t.string :state
      t.string :postcode                        
      t.string :homephone
      t.timestamps
    end
  end
end 

我在schame.rb中删除了旧的development.sqlite3和旧架构 假设我添加了几列,但在模型中缺少这些列。

但我的模特仍然是

class Student < ActiveRecord::Base
  attr_accessible :firstname,:lastname,:account,
end

我是否可以通过简单的方法将新迁移脚本中的更改用于建模?

3 个答案:

答案 0 :(得分:2)

如果您想允许其他属性的批量分配,您只需将密钥添加到attr_accessible

class Student < ActiveRecord::Base
  attr_accessible :firstname,:lastname,:account,:address, :city, :state, :postcode, :homephone
end

但是,您的模型仍然具有这些属性(或您调用它们的列)。你不能先进行质量分配(比如create或update_attributes)而不先让它们成为attr_accessible。

答案 1 :(得分:1)

看起来你可能rails generate migration并不意味着影响你的模型。我相信在您创建模型之后,所有事情都必须手动完成。

如果您真的想同时对数据库和模型进行更改,最好的办法是删除迁移和模型并执行rails generate scaffolddocumentation)来创建整个数据库和模型脚手架从头开始。

答案 2 :(得分:0)

在模型中手动添加新列没有问题。