2016-06-28 63 views
0

我有一個名爲categories的模型,當前它們屬於product,但我希望它們屬於store。我有幾千這些,所以我想要做的是創建一個遷移,將store_id添加到類別,然後從它當前的關聯獲取關聯的product.store.id,並將其添加到store_id。之後,我想刪除產品關聯。用於更改belongs_to協會的遷移

有沒有人知道如何輕鬆和安全地實現呢?

回答

0

你有你不想失去列數據,然後使用rename_column

+0

但我還是要更改的值。由於product_id明顯不符合store_id –

0

您可以再補充新的遷移,這將創建一個類別,存儲新的參考。

class YourMigrationName < ActiveRecord::Migration 
    def up 
    add_reference :categories, :store, index: true 
    Category.all.each do |category| 
     category.store_id = category.product_id 
     category.save 
    end 
    remove_column :product_id 
    end 

    def down 
    add_reference :categories, :product, index: true 
    Category.all.each do |category| 
     category.product_id = category.store_id 
     category.save 
    end 
    remove_reference :categories, :store, index: true 
    end 
end 

可能是,如果你已經添加了產品的參考和索引然後寫一樣的店這樣的話它會刪除索引爲好。

0

首先重命名列STORE_ID,

rename_column :categories, :product_id, :store_id 

然後改變assosciation。

現在您可以編寫一個rake任務來傳輸數據,也可以通過控制檯手動執行。 這是寫rake任務的更好方法。

根據您的要求,您的耙子任務可以是,從產品中獲取商店並根據您的要求分配到類別。

require 'rake' 

    namespace :category do 
     task :product_to_store => :environment do 
      Category.all.each do |category| 
       product = Product.find(category.store_id) //you will get product,as now it chnaged to store_id 
       if product.present? 
        category.store_id = product.try(:store).try(:id) //assign the product's store_id to the category, use try to reject errored records 
        category.save 
       end  
      end 
     end 
    end 

Now run, **`rake category:product_to_store`**, thats it, the data gets transfered. 
1

如果您添加在錯誤的方向上的關聯,您可以使用change_table扭轉協會:

class CreateFavorites < ActiveRecord::Migration[5.0] 
    def change 
    create_table :favorites do |t| 
     t.belongs_to :article 

     t.timestamps 
    end 
    end 
end 


class RemoveArticleFromFavorites < ActiveRecord::Migration[5.0] 
    def change 
    change_table :favorites do |t| 
     t.remove_references :article 
    end 
    end 
end 

class AddFavoriteToArticles < ActiveRecord::Migration[5.0] 
    def change 
    change_table :article do |t| 
     t.belongs_to :favorite 
    end 
    end 
end