Skip to content

Commit

Permalink
Create table in same database as superclass
Browse files Browse the repository at this point in the history
  • Loading branch information
joelind authored and nertzy committed Jan 2, 2025
1 parent f925b17 commit 93c089e
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 6 deletions.
2 changes: 1 addition & 1 deletion lib/with_model/model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def stubber
end

def table
@table ||= Table.new table_name, @table_options, &@table_block
@table ||= Table.new table_name, @table_options, connection: @superclass.connection, &@table_block
end

def table_name
Expand Down
10 changes: 5 additions & 5 deletions lib/with_model/table.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ module WithModel
class Table
# @param [Symbol] name The name of the table to create.
# @param options Passed to ActiveRecord `create_table`.
# @param connection The connection to use for creating the table.
# @param block Passed to ActiveRecord `create_table`.
# @see https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-create_table
def initialize(name, options = {}, &block)
def initialize(name, options = {}, connection: ActiveRecord::Base.connection, &block)
@name = name.freeze
@options = options.freeze
@block = block
@connection = connection
end

# Creates the table with the initialized options. Drops the table if
Expand All @@ -29,16 +31,14 @@ def destroy

private

attr_reader :connection

def exists?
if connection.respond_to?(:data_source_exists?)
connection.data_source_exists?(@name)
else
connection.table_exists?(@name)
end
end

def connection
ActiveRecord::Base.connection
end
end
end
21 changes: 21 additions & 0 deletions spec/with_model_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -387,4 +387,25 @@ class BlogPostParent < ActiveRecord::Base
expect(BlogPost.with_model?).to be true
end
end

context "with 'superclass' that connects to a different database" do
class ApplicationRecordInDifferentDatabase < ActiveRecord::Base
self.abstract_class = true
establish_connection(ActiveRecord::Base.connection_pool.db_config.configuration_hash)
end

after(:all) do
Object.__send__(:remove_const, 'ApplicationRecordInDifferentDatabase')
end

with_model :BlogPost, superclass: ApplicationRecordInDifferentDatabase do
table do |t|
t.string 'title'
end
end

it 'uses the superclass connection' do
expect(BlogPost.connection.tables).to include(BlogPost.table_name)
end
end
end

0 comments on commit 93c089e

Please sign in to comment.