手动更新模型后更新db / migrate?
例如,我有这个模型:
class Product < ActiveRecord::Base attr_accessible :name, :order end
然后,当我做rake db:migrate
它创建了这个db / migrate / 20120825132038_create_products.rb :
class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.integer :order t.string :name t.timestamps end end end
但这一切都发生了因为我使用了rails generate Product order:integer name:string
现在我转到产品型号并手动更改为:
class Product < ActiveRecord::Base attr_accessible :name, :order, :category_id validates :name, uniqueness: true belongs_to :category end
如何使用更新自动更新db / migrate / 20120825132038_create_products.rb ?
运行rake db:migrate
,它没有创建db/migrate/20120825132038_create_products.rb
。 您运行时创建了该迁移文件
rails generate Product order:integer name:string
attr_accessible
与迁移数据库无关。
我强烈建议您阅读有关迁移的Rails指南,以及有关attr_accessible
Mass Assignment部分。
要生成新的迁移文件(因为您的问题中提到的文件已经由您提到的上一个rake db:migrate
命令处理) ,运行
rails g migration AddCategoryIdToProduct category_id:integer
这应该生成一个包含内容的新迁移
class AddCategoryIdToProduct < ActiveRecord::Migration def change add_column :products, :category_id, :integer end end
现在再次运行rake db:migrate
将处理此迁移文件,将新的category_id
整数列添加到products
表中。
您可以通过运行重做迁移
rake db:migrate:up VERSION=20121031143418 #insert the timestamp on migration
您也可以重做一次迁移(上下运行,但只有在你有一个向上和向下的情况下才能运行,当你只有一个变化时就不会这样做)
rake db:migrate:redo
- Ruby on Rails:全function无表格模型
- 如何在具有名为“valid”的列的数据库上使用ActiveRecord? (DangerousAttributeError)
- 为什么Rails模型关联结果不是自然的ActiveRecord :: Relations?
- 动态创建查询 – Rails 5
- 在使用连接表时,如何处理重复的副作用 – 即回报友谊等
- Rails模型关联,has_many:through和has_one具有相同的模型
- 返回自定义查询在activerecord中选择
- 你会如何使用Squeel进行这个Rails子查询?
- 如何确保不通过activerecords将重复的行添加到我的数据库表中?