提交 a013b082 编写于 作者: S Stefan Kanev

create_join_table uses same logic as HABTM reflections

Before this change, create_join_table would not remove the common prefix
in the join table name, unlike ActiveRecord::Reflections. A HABTM
between Music::Artist and Music::Record would use a table
music_artists_records, while create_join table would create
music_artists_music_records.
上级 843b8c0b
* `create_join_table` removes a common prefix when generating the join table.
This matches the existing behavior of HABTM associations.
Fixes #13683.
*Stefan Kanev*
* Dont swallow errors on compute_type when having a bad alias_method on
a class.
......
......@@ -8,7 +8,7 @@ def find_join_table_name(table_1, table_2, options = {})
end
def join_table_name(table_1, table_2)
[table_1.to_s, table_2.to_s].sort.join("_").to_sym
ModelSchema.derive_join_table_name(table_1, table_2).to_sym
end
end
end
......
......@@ -55,6 +55,17 @@ module ModelSchema
delegate :type_for_attribute, to: :class
end
# Derives the join table name for +first_table+ and +second_table+. The
# table names appear in alphabetical order. A common prefix is removed
# (useful for namespaced models like Music::Artist and Music::Record):
#
# artists, records => artists_records
# records, artists => artists_records
# music_artists, music_records => music_artists_records
def self.derive_join_table_name(first_table, second_table) # :nodoc:
[first_table.to_s, second_table.to_s].sort.join("\0").gsub(/^(.*_)(.+)\0\1(.+)/, '\1\2_\3').gsub("\0", "_")
end
module ClassMethods
# Guesses the table name (in forced lower-case) based on the name of the class in the
# inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy
......
......@@ -567,7 +567,7 @@ def derive_foreign_key
end
def derive_join_table
[active_record.table_name, klass.table_name].sort.join("\0").gsub(/^(.*_)(.+)\0\1(.+)/, '\1\2_\3').gsub("\0", "_")
ModelSchema.derive_join_table_name active_record.table_name, klass.table_name
end
def primary_key(klass)
......
......@@ -119,6 +119,30 @@ def test_drop_join_table_with_column_options
assert !connection.tables.include?('artists_musics')
end
def test_create_and_drop_join_table_with_common_prefix
with_table_cleanup do
connection.create_join_table 'audio_artists', 'audio_musics'
assert_includes connection.tables, 'audio_artists_musics'
connection.drop_join_table 'audio_artists', 'audio_musics'
assert !connection.tables.include?('audio_artists_musics'), "Should have dropped join table, but didn't"
end
end
private
def with_table_cleanup
tables_before = connection.tables
yield
ensure
tables_after = connection.tables - tables_before
tables_after.each do |table|
connection.execute "DROP TABLE #{table}"
end
end
end
end
end
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册