2014-03-13 118 views
0

我的應用程序中有一個has_many關係。例如部門有很多用戶。 我想將它轉換爲has_and_belongs_to_many關係。 作爲遷移的一部分,我需要保留用戶和部門之間的當前關係,這意味着我必須將所有數據移動到新的連接表中。 這是我創建的遷移:將has_many關係轉換爲has_and_belongs_to_many的最佳方法是什麼?

class CreateUserDepartment < ActiveRecord::Migration 
    def change 
    create_table :users_departments do |t| 
     t.belongs_to :user 
     t.belongs_to :department 
    end 

    ############################################### 
    # need to move the data to the new table here # 
    ############################################### 

    remove_column :users, :sub_department_id 
    end 

end 

什麼是寫缺失行的最好方法?

回答

1

如果必須,您可以使用execute "your SQL"。看到這個問題:

How do I add some inserts in rails migration?

「不」回答這個問題的主要價值是在解釋爲什麼你不想用你的模型來做到這一點。此外,如果您可以或者想要使用change來做到這一點,我會很驚訝,您可能需要使用self.up

相關問題