Convertig a HABTM join table to a real activerecord model

If your has_and_belongs_to_many associations suddenly need to know more, its time to convert them to a real model.

  • rename table
  • add id
  • add created_at/updated_at as not-null (need to set existing records to something)

Code

class CreateJoinModel < ActiveRecord::Migration
  def change
    rename_table :products_users, :purchases
    add_column :purchases, :id, :primary_key
    [:created_at, :updated_at].each do |column|
      add_column :purchases, column, :timestamp, null: false, default: Time.at(0)
      change_column_default :purchases, column, nil
    end
  end
end

Leave a comment