Skip to content

Commit

Permalink
Merge pull request #248 from greysteil/foreign-keys
Browse files Browse the repository at this point in the history
Add foreign keys when creating a new transition table
  • Loading branch information
Sinjo authored May 22, 2017
2 parents bf89b2d + 9b9f9e9 commit 41419af
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/generators/statesman/generator_helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions lib/generators/statesman/templates/create_migration.rb.erb
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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') }
Expand Down

0 comments on commit 41419af

Please sign in to comment.