Skip to content

Commit 0fe2863

Browse files
committed
Make engines aware of AR::Base table name prefix
1 parent c057eda commit 0fe2863

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

railties/CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
* Fix isolated engines to take `ActiveRecord::Base.table_name_prefix` into consideration.
2+
This will allow for engine defined models, such as inside Active Storage, to respect
3+
Active Record table name prefix configuration.
4+
5+
*Chedli Bourguiba*
6+
17
* Fix running `db:system:change` when app has no Dockerfile.
28

39
*Hartley McGuire*

railties/lib/rails/engine.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,12 @@ def isolate_namespace(mod)
396396

397397
unless mod.respond_to?(:table_name_prefix)
398398
define_method(:table_name_prefix) { "#{name}_" }
399+
400+
ActiveSupport.on_load(:active_record) do
401+
mod.singleton_class.redefine_method(:table_name_prefix) do
402+
"#{ActiveRecord::Base.table_name_prefix}#{name}_"
403+
end
404+
end
399405
end
400406

401407
unless mod.respond_to?(:use_relative_model_naming?)

railties/test/railties/engine_test.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1290,6 +1290,32 @@ class Engine < ::Rails::Engine
12901290
assert_equal "foo", Bukkits.table_name_prefix
12911291
end
12921292

1293+
test "take ActiveRecord table_name_prefix into consideration when defining table_name_prefix" do
1294+
@plugin.write "lib/bukkits.rb", <<-RUBY
1295+
module Bukkits
1296+
class Engine < ::Rails::Engine
1297+
isolate_namespace(Bukkits)
1298+
end
1299+
end
1300+
RUBY
1301+
1302+
@plugin.write "app/models/bukkits/post.rb", <<-RUBY
1303+
module Bukkits
1304+
class Post < ActiveRecord::Base
1305+
end
1306+
end
1307+
RUBY
1308+
1309+
add_to_config <<-RUBY
1310+
config.active_record.table_name_prefix = "ar_prefix_"
1311+
RUBY
1312+
1313+
boot_rails
1314+
1315+
assert_equal "ar_prefix_bukkits_posts", Bukkits::Post.table_name
1316+
assert_equal "ar_prefix_bukkits_", Bukkits.table_name_prefix
1317+
end
1318+
12931319
test "fetching engine by path" do
12941320
@plugin.write "lib/bukkits.rb", <<-RUBY
12951321
module Bukkits

0 commit comments

Comments
 (0)