Skip to content

Commit 3675cee

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 770f3ed commit 3675cee

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

lib/json_translate/translates.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def translates(*attrs)
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)

test/test_helper.rb

Lines changed: 12 additions & 0 deletions
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

test/translates_test.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,14 @@ def test_with_translation_relation
206206
end
207207
end
208208

209+
def test_with_translation_when_ambiguous_column
210+
p = Post.create!(:title_translations => { "en" => "Alice in Wonderland", "fr" => "Alice au pays des merveilles" })
211+
Tag.create!(:title_translations => { "en" => "A Tag", "fr" => "Un tag" }, post: p)
212+
I18n.with_locale(:en) do
213+
assert_equal p.title_en, Post.tagged("A Tag").first.try(:title)
214+
end
215+
end
216+
209217
def test_with_interpolation_arguments
210218
p = Post.create!(:title_translations => { "en" => "Alice in %{where}" })
211219
I18n.with_locale(:en) do

0 commit comments

Comments
 (0)