手动更新模型后更新数据库/迁移? [英] Update db/migrate after manually updating models?

查看:24
本文介绍了手动更新模型后更新数据库/迁移?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有这个模型:

class Product 

然后当我执行 rake db:migrate 时,它创建了这个 db/migrate/20120825132038_create_products.rb:

class CreateProducts ActiveRecord::迁移定义改变create_table :产品做 |t|t.整数:顺序t.string :namet.时间戳结尾结尾结尾

但这一切都发生了,因为我使用了 rails generate Product order:integer name:string

现在在我转到产品模型并将其手动更改为:

class Product 

如何使用更新自动更新 db/migrate/20120825132038_create_products.rb?

解决方案

当你运行 rake db:migrate 时,它没有创建 db/migrate/20120825132038_create_products.rb.该迁移文件是在您运行时创建的

rails 生成产品顺序:整数名称:字符串

attr_accessible 与迁移数据库无关.

我强烈建议您阅读关于迁移的 Rails 指南,以及作为 Mass Assignment 的部分,它讨论了 attr_accessible.

生成迁移文件(因为您的问题中提到的文件已经被您提到的之前的 rake db:migrate 命令处理过),运行

rails g 迁移 AddCategoryIdToProduct category_id:integer

这应该会生成一个包含类似内容的新迁移

class AddCategoryIdToProduct 

现在再次运行 rake db:migrate 将处理这个迁移文件,将新的 category_id 整数列添加到您的 products 表中.>

For example i have this model:

class Product < ActiveRecord::Base
  attr_accessible :name, :order
end

Then when i did rake db:migrate it created this 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

But it all happend cuz i used rails generate Product order:integer name:string

Now after i go to Product model and changes it manually to:

class Product < ActiveRecord::Base
  attr_accessible :name, :order, :category_id

  validates :name, uniqueness: true
  belongs_to :category
end

How can i auto update the db/migrate/20120825132038_create_products.rb with the updates?

解决方案

When you ran rake db:migrate, it did not create db/migrate/20120825132038_create_products.rb. That migration file was created when you ran

rails generate Product order:integer name:string

attr_accessible has nothing to do with migrating your database.

I strongly recommend you read the Rails Guide on Migrations, as well as the section on Mass Assignment which discusses attr_accessible.

To generate a new migration file (since the one mentioned in your Question has already been processed by the previous rake db:migrate command you mentioned running), run

rails g migration AddCategoryIdToProduct category_id:integer

This should generate a new migration with contents like

class AddCategoryIdToProduct < ActiveRecord::Migration
  def change
    add_column :products, :category_id, :integer
  end
end

Running rake db:migrate again now will process this migration file, adding the new category_id integer column to your products table.

这篇关于手动更新模型后更新数据库/迁移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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