簡體   English   中英

遷移以更改belongs_to關聯

[英]Migration for changing belongs_to association

我有一個名為categories的模型,目前它們屬於product但我希望它們屬於store 我有幾千個這樣的,所以我想做的是創建一個遷移,將store_id添加到類別,然后從它的當前關聯中獲取關聯的product.store.id並將其添加到store_id 之后,我想刪除產品關聯。

有誰知道如何輕松安全地實現這一目標?

如果以錯誤的方向添加關聯,可以使用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

如果您不希望丟失列中的數據,請使用rename_column

您可以添加新的遷移,該遷移將使用類別作為商店創建新引用。

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM