diff --git a/lib/generators/statesman/generator_helpers.rb b/lib/generators/statesman/generator_helpers.rb index a0ec18b2..b9ad87e3 100644 --- a/lib/generators/statesman/generator_helpers.rb +++ b/lib/generators/statesman/generator_helpers.rb @@ -20,6 +20,10 @@ def parent_name parent.demodulize.underscore end + def parent_table_name + parent.demodulize.underscore.pluralize + end + def parent_id parent_name + "_id" end diff --git a/lib/generators/statesman/templates/create_migration.rb.erb b/lib/generators/statesman/templates/create_migration.rb.erb index a2ac369b..f958871c 100644 --- a/lib/generators/statesman/templates/create_migration.rb.erb +++ b/lib/generators/statesman/templates/create_migration.rb.erb @@ -9,6 +9,9 @@ class Create<%= migration_class_name %> < ActiveRecord::Migration t.timestamps null: false end + # Foreign keys are optional, but highly recommended + add_foreign_key :<%= table_name %>, :<%= parent_table_name %> + add_index(:<%= table_name %>, [:<%= parent_id %>, :sort_key], unique: true, diff --git a/spec/generators/statesman/active_record_transition_generator_spec.rb b/spec/generators/statesman/active_record_transition_generator_spec.rb index 88e5a6bf..7943d036 100644 --- a/spec/generators/statesman/active_record_transition_generator_spec.rb +++ b/spec/generators/statesman/active_record_transition_generator_spec.rb @@ -7,6 +7,20 @@ let(:migration_name) { 'db/migrate/create_bacon_transitions.rb' } end + describe 'creates a migration' do + subject { file("db/migrate/#{time}_create_bacon_transitions.rb") } + + before { allow(Time).to receive(:now).and_return(mock_time) } + before { run_generator %w(Yummy::Bacon Yummy::BaconTransition) } + + let(:mock_time) { double('Time', utc: double('UTCTime', strftime: time)) } + let(:time) { '5678309' } + + it "includes a foreign key" do + expect(subject).to contain("add_foreign_key :bacon_transitions, :bacons") + end + end + describe 'properly adds class names' do before { run_generator %w(Yummy::Bacon Yummy::BaconTransition) } subject { file('app/models/yummy/bacon_transition.rb') }