Skip to content

Commit 823019c

Browse files
committed
Include the table name in the with_x_translation
This is to prevent a possible ambiguous column error when the model is joined with another model having the same translated column name.
1 parent d146557 commit 823019c

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

Diff for: lib/json_translate/translates.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def translates(*attrs, allow_blank: false)
3939
end
4040

4141
define_singleton_method "with_#{attr_name}_translation" do |value, locale = I18n.locale|
42-
quoted_translation_store = connection.quote_column_name("#{attr_name}#{SUFFIX}")
42+
quoted_translation_store = connection.quote_table_name("#{self.table_name}.#{attr_name}#{SUFFIX}")
4343
translation_hash = { "#{locale}" => value }
4444

4545
if MYSQL_ADAPTERS.include?(connection.adapter_name)

Diff for: test/test_helper.rb

+12
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,15 @@
77
I18n.available_locales = [:en, :fr]
88

99
class Post < ActiveRecord::Base
10+
has_many :tags
1011
translates :title, :body_1
12+
13+
scope :tagged, -> (tag_title) { joins(:tags).merge(Tag.with_title_translation(tag_title)) }
14+
end
15+
16+
class Tag < ActiveRecord::Base
17+
belongs_to :post
18+
translates :title
1119
end
1220

1321
class PostDetailed < Post
@@ -53,6 +61,10 @@ def create_table
5361
t.column :body_1_translations, column_type
5462
t.column :comment_translations, column_type
5563
end
64+
connection.create_table(:tags, :force => true) do |t|
65+
t.column :title_translations, column_type
66+
t.column :post_id, :integer
67+
end
5668
end
5769
end
5870

Diff for: test/translates_test.rb

+8
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,14 @@ def test_with_translation_relation
238238
end
239239
end
240240

241+
def test_with_translation_when_ambiguous_column
242+
p = Post.create!(:title_translations => { "en" => "Alice in Wonderland", "fr" => "Alice au pays des merveilles" })
243+
Tag.create!(:title_translations => { "en" => "A Tag", "fr" => "Un tag" }, post: p)
244+
I18n.with_locale(:en) do
245+
assert_equal p.title_en, Post.tagged("A Tag").first.try(:title)
246+
end
247+
end
248+
241249
def test_with_interpolation_arguments
242250
p = Post.create!(:title_translations => { "en" => "Alice in %{where}" })
243251
I18n.with_locale(:en) do

0 commit comments

Comments
 (0)