将raails表从belongs_to迁移到has_and_belongs_to_many

lin*_*ndy 4 postgresql ruby-on-rails database-migration

目前,我有users包含client_id(所以,a User belongs_to :client)的表.

我们需要支持与用户关联的多个客户端,因此我们实现了一个User has_and_belongs_to_many :clients关联.为此,我们:

  • 创建了一个新的clients_users表,用user_idclient_id列;
  • client_id从... 删除users.

现在,我们如何为表中client_id最初的每个记录自动创建HABTM记录users?我们不想丢失数据.

我不知道从哪里开始,因为db:migrate不应该涉及它们之间的模型或关联,并且在我的情况下执行原始查询可能会变得复杂.

y.b*_*gey 6

只需添加新的has_and_belongs_to_many关联UserClient模型,然后运行以下迁移.

此解决方案来自http://manuelvanrijn.nl/blog/2013/03/04/rails-belongs-to-to-has-many/

class MultipleClientsForUser < ActiveRecord::Migration
  def up
    create_table :clients_users, id: false do |t|
      t.references :client, :user
    end

    # define the old belongs_to client associate
    User.class_eval do
      belongs_to :single_client, class_name: "Client", foreign_key: "client_id"
    end

    # add the belongs_to client to the has_and_belongs_to_many client
    User.find_each do |user|
      unless user.single_client.nil?
        user.clients << user.single_client
        user.save
      end
    end

    # remove the old client_id column for the belongs_to associate
    remove_column :users, :client_id
  end

  def down
    add_column :users, :client_id, :integer

    User.class_eval do
      belongs_to :single_client, class_name: "Client", foreign_key: "client_id"
    end

    #Note that only one client may be restored in rollback
    User.find_each do |user|
      user.single_client = user.clients.first unless user.clients.empty?
      user.save
    end

    drop_table :clients_users
  end
end
Run Code Online (Sandbox Code Playgroud)