Rails doesn’t include timestamps in join tables by default but sometimes it’s nice to see when a relationship was formed. Knowing when these relationships are formed can be helpful for auditing purposes and may be useful to expose within your application.
To create a join table write a migration like the one below in your terminal.
rails generate migration CreateJoinTableCatsOwners cats owners
Which will result in a migration which looks like this:
class CreateJoinTableCatsOwners < ActiveRecord::Migration[7.0]
def change
create_join_table :cats, :owners do |t|
t.index [:cat_id, :owner_id]
t.index [:owner_id, :cat_id]
end
end
end
So you can see that by default timestamps aren’t included in this migration so let’s go ahead and amend the above migration and add some timestamps:
class CreateJoinTableCatsOwners < ActiveRecord::Migration[7.0]
def change
create_join_table :cats, :owners do |t|
t.index [:cat_id, :owner_id]
t.index [:owner_id, :cat_id]
t.timestamps
end
end
end
This will add the timestamps to your join table and allow you to use the created_at and updated_at fields.
What if you want to add timestamps to a join table which already exists? You’ll need to create another migration to do this for you:
rails generate migration AddTimestampsToCatsOwners
This will create an empty migration which you can edit to include timestamps:
class AddTimestampsToCatsOwners < ActiveRecord::Migration[7.0]
def change
add_timestamps :cats_owners, default: Time.zone.now
change_column_default :cats_owners, :created_at, nil
change_column_default :cats_owners, :updated_at, nil
end
end
Setting the default when adding the timestamps will ensure that if you have any existing records that they will have a timestamp applied albeit not an accurate one.