From c124808ffe53aa1771536dc4339536aa24119441 Mon Sep 17 00:00:00 2001 From: Philipp Fischbeck Date: Thu, 12 Feb 2015 16:31:52 +0100 Subject: [PATCH 1/2] Fix #14: Make uniqueness check among other problems --- app/models/translation.rb | 11 ++++++++++- test/models/translation_test.rb | 9 +++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/app/models/translation.rb b/app/models/translation.rb index 8253535..76e197a 100644 --- a/app/models/translation.rb +++ b/app/models/translation.rb @@ -2,7 +2,16 @@ class Translation < ActiveRecord::Base belongs_to :problem, inverse_of: :translations validates :title, :content, :problem_id, presence: true - validates :title, uniqueness: true + validate :title_is_unique_among_other_problems self.per_page = 50 + + def title_is_unique_among_other_problems + Problem.where.not(id: problem_id).each do |problem| + if problem.is_translated? and problem.title == title + errors.add(:title, :taken) + break + end + end + end end diff --git a/test/models/translation_test.rb b/test/models/translation_test.rb index 5549ff0..3deb421 100644 --- a/test/models/translation_test.rb +++ b/test/models/translation_test.rb @@ -20,6 +20,15 @@ class TranslationTest < ActiveSupport::TestCase assert_not translation.save end + test "should save translation with duplicate title of translation for same problem" do + translation = Translation.new( + title: translations(:translation_one).title, + content: 'This is some content', + problem_id: 1 + ) + assert translation.save + end + test "should save correct translation" do translation = Translation.new( title: 'A unique title', From b1d0daf47ad7f674d877f2ed3994eaa33b64a18a Mon Sep 17 00:00:00 2001 From: Philipp Fischbeck Date: Thu, 12 Feb 2015 18:26:02 +0100 Subject: [PATCH 2/2] Prevent N+1 on title validation --- app/models/translation.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/translation.rb b/app/models/translation.rb index 76e197a..9bd5719 100644 --- a/app/models/translation.rb +++ b/app/models/translation.rb @@ -7,7 +7,7 @@ class Translation < ActiveRecord::Base self.per_page = 50 def title_is_unique_among_other_problems - Problem.where.not(id: problem_id).each do |problem| + Problem.includes(:translation).where.not(id: problem_id).each do |problem| if problem.is_translated? and problem.title == title errors.add(:title, :taken) break