Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create table in same database as superclass #49

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -391,4 +391,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