,比如我有這種模式:手動更新模型後更新db/migrate?
class Product < ActiveRecord::Base
attr_accessible :name, :order
end
然後當我做了rake db:migrate
創造了這個DB /遷移/ 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
但是這一切happend因爲我使用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?
感謝您的偉大的消除! 但每次我想添加一個屬性/屬性(無論你怎麼稱呼它)到一個模型中,我需要使用rails g migration並創建一個新類? – Danpe
如果遷移已經應用到數據庫,** yes **。模型只不過是一個可以與數據庫進行交互的界面。它不會操縱數據庫的**結構**;這就是遷移的目的。將一列添加到表格中會自動使相關模型中的新屬性方法可用。 – deefour
是的。始終創建新的遷移 - 即使只有一列。永遠不要回頭編輯舊的遷移。這是一個好習慣! 相信我,你未來的同事會感謝我確保你遵循這種做法。 –