国产一区二区精品久久_蜜桃狠狠狠狠狠狠狠狠狠_午夜视频精品_激情都市一区二区

當前位置:首頁 > 網站舊欄目 > 學習園地 > 設計軟件教程 > 每天一劑Rails良藥之Safely Use Models in Migrations

每天一劑Rails良藥之Safely Use Models in Migrations
2010-01-14 07:03:16  作者:  來源:
我們平時做Migrations時除了更改schema,還經常需要更改data
但我們以前的Migrations可能不工作,因為data之間可能有依賴關系
我們可以通過在Migrations里定義Model來解決該問題:
Java代碼 復制代碼
  1. class AddPositionToProducts < ActiveRecord::Migration   
  2.   class Product < ActiveRecord::Base; end   
  3.   class SoftwareProduct < Product; end   
  4.   class CourseProduct < Product; end   
  5.   
  6.   def self.up   
  7.     add_column :products, :position, :integer   
  8.     Product.reset_column_information   
  9.     SoftwareProduct.find(:all).inject(0do |i, p|   
  10.       p.update_attribute(:position, i)   
  11.        i+1  
  12.     end   
  13.     CourseProduct.find(:all).inject(0do |i, p|   
  14.       p.update_attribute(:position, i)   
  15.       i+1  
  16.     end   
  17.   end   
  18.   
  19.   def self.down   
  20.     remove_column :products, :position   
  21.   end   
  22. end  

這里我們在Migration里面定義Model,相當于給Model加了一個名字空間AddPositionToProducts::Product,這就能保證該Model在你的migrations里是唯一的

安徽新華電腦學校專業職業規劃師為你提供更多幫助【在線咨詢