ruby-on-rails – 手动更新模型后更新db / migrate?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 手动更新模型后更新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产品顺序:整数名称:字符串

现在我转到产品型号并手动更改为:

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与迁移数据库无关.

我强烈建议您阅读Migrations上的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表中.

原文链接:https://www.f2er.com/ruby/269381.html

猜你在找的Ruby相关文章