Commit 0df8e456b1ccae787e2b69ddef78f8ec0152563c
Committed by
Daniela Feitosa
1 parent
16dd16e5
Exists in
master
and in
29 other branches
Not allow self and cyclical reference in article paternity
Showing
2 changed files
with
37 additions
and
0 deletions
Show diff stats
app/models/article.rb
@@ -79,6 +79,25 @@ class Article < ActiveRecord::Base | @@ -79,6 +79,25 @@ class Article < ActiveRecord::Base | ||
79 | validate :native_translation_must_have_language | 79 | validate :native_translation_must_have_language |
80 | validate :translation_must_have_language | 80 | validate :translation_must_have_language |
81 | 81 | ||
82 | + validate :no_self_reference | ||
83 | + validate :no_cyclical_reference, :if => 'parent_id.present?' | ||
84 | + | ||
85 | + def no_self_reference | ||
86 | + errors.add(:parent_id, _('self-reference is not allowed.')) if id && parent_id == id | ||
87 | + end | ||
88 | + | ||
89 | + def no_cyclical_reference | ||
90 | + current_parent = Article.find(parent_id) | ||
91 | + while current_parent | ||
92 | + if current_parent == self | ||
93 | + errors.add(:parent_id, _('cyclical reference is not allowed.')) | ||
94 | + break | ||
95 | + end | ||
96 | + current_parent = current_parent.parent | ||
97 | + end | ||
98 | + end | ||
99 | + | ||
100 | + | ||
82 | def is_trackable? | 101 | def is_trackable? |
83 | self.published? && self.notifiable? && self.advertise? && self.profile.public_profile | 102 | self.published? && self.notifiable? && self.advertise? && self.profile.public_profile |
84 | end | 103 | end |
test/unit/article_test.rb
@@ -1800,4 +1800,22 @@ class ArticleTest < ActiveSupport::TestCase | @@ -1800,4 +1800,22 @@ class ArticleTest < ActiveSupport::TestCase | ||
1800 | assert_equal [f2.path,article.slug].join('/'), article.path | 1800 | assert_equal [f2.path,article.slug].join('/'), article.path |
1801 | end | 1801 | end |
1802 | 1802 | ||
1803 | + should 'not allow parent as itself' do | ||
1804 | + article = Article.create!(:name => 'Sample Article', :profile => profile) | ||
1805 | + article.parent = article | ||
1806 | + article.valid? | ||
1807 | + | ||
1808 | + assert article.errors.invalid?(:parent_id) | ||
1809 | + end | ||
1810 | + | ||
1811 | + should 'not allow cyclical paternity' do | ||
1812 | + a1 = Article.create!(:name => 'Sample Article 1', :profile => profile) | ||
1813 | + a2 = Article.create!(:name => 'Sample Article 2', :profile => profile, :parent => a1) | ||
1814 | + a3 = Article.create!(:name => 'Sample Article 3', :profile => profile, :parent => a2) | ||
1815 | + a1.parent = a3 | ||
1816 | + a1.valid? | ||
1817 | + | ||
1818 | + assert a1.errors.invalid?(:parent_id) | ||
1819 | + end | ||
1820 | + | ||
1803 | end | 1821 | end |