用于更改belongs_to协会的迁移

问题描述:

我有一个名为categories的模型,当前它们属于product,但我希望它们属于store。我有几千这些,所以我想要做的是创建一个迁移,将store_id添加到类别,然后从它当前的关联获取关联的product.store.id,并将其添加到store_id。之后,我想删除产品关联。用于更改belongs_to协会的迁移

有没有人知道如何轻松和安全地实现呢?

你有你不想失去列数据,然后使用rename_column

+0

但我还是要更改的值。由于product_id明显不符合store_id –

您可以再补充新的迁移,这将创建一个类别,存储新的参考。

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 

可能是,如果你已经添加了产品的参考和索引然后写一样的店这样的话它会删除索引为好。

首先重命名列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. 

如果您添加在错误的方向上的关联,您可以使用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