【问题标题】:What is the best way to convert a has_many relation to has_and_belongs_to_many?将 has_many 关系转换为 has_and_belongs_to_many 的最佳方法是什么?
【发布时间】:2014-03-13 15:48:33
【问题描述】:

我的应用中有一个 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

什么是写缺失行的最佳方法?

【问题讨论】:

    标签: ruby-on-rails database-migration


    【解决方案1】:

    如果必须,您可以使用execute "your SQL"。看到这个问题:

    How do I add some inserts in rails migration?

    对该问题的“不”回答的主要价值在于解释为什么您不想使用您的模型来执行此操作。此外,如果您可以或想要使用 change 执行此操作,我会感到惊讶,您可能需要使用 self.up

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多