1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

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.
This commit is contained in:
Stefan Kanev 2014-07-18 19:46:53 +03:00
parent 843b8c0b8c
commit a013b082aa
5 changed files with 44 additions and 2 deletions

View file

@ -1,3 +1,10 @@
* `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.

View file

@ -8,7 +8,7 @@ module ActiveRecord
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

View file

@ -55,6 +55,17 @@ module ActiveRecord
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

View file

@ -567,7 +567,7 @@ Joining, Preloading and eager loading of these associations is deprecated and wi
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)

View file

@ -119,6 +119,30 @@ module ActiveRecord
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