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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s