Skip to content

Commit

Permalink
Include the table name in the with_x_translation
Browse files Browse the repository at this point in the history
This is to prevent a possible ambiguous column error when the model is joined
with another model having the same translated column name.
  • Loading branch information
louim committed Feb 23, 2021
1 parent d146557 commit 823019c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/json_translate/translates.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def translates(*attrs, allow_blank: false)
end

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

if MYSQL_ADAPTERS.include?(connection.adapter_name)
Expand Down
12 changes: 12 additions & 0 deletions test/test_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,15 @@
I18n.available_locales = [:en, :fr]

class Post < ActiveRecord::Base
has_many :tags
translates :title, :body_1

scope :tagged, -> (tag_title) { joins(:tags).merge(Tag.with_title_translation(tag_title)) }
end

class Tag < ActiveRecord::Base
belongs_to :post
translates :title
end

class PostDetailed < Post
Expand Down Expand Up @@ -53,6 +61,10 @@ def create_table
t.column :body_1_translations, column_type
t.column :comment_translations, column_type
end
connection.create_table(:tags, :force => true) do |t|
t.column :title_translations, column_type
t.column :post_id, :integer
end
end
end

Expand Down
8 changes: 8 additions & 0 deletions test/translates_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,14 @@ def test_with_translation_relation
end
end

def test_with_translation_when_ambiguous_column
p = Post.create!(:title_translations => { "en" => "Alice in Wonderland", "fr" => "Alice au pays des merveilles" })
Tag.create!(:title_translations => { "en" => "A Tag", "fr" => "Un tag" }, post: p)
I18n.with_locale(:en) do
assert_equal p.title_en, Post.tagged("A Tag").first.try(:title)
end
end

def test_with_interpolation_arguments
p = Post.create!(:title_translations => { "en" => "Alice in %{where}" })
I18n.with_locale(:en) do
Expand Down

0 comments on commit 823019c

Please sign in to comment.