Skip to content

Commit 021e33a

Browse files
committed
Prevent ontology term links being recreated on every update. Fixes #1270
1 parent e67ce73 commit 021e33a

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

lib/has_ontology_terms.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,26 @@ def has_ontology_terms(association_name, ontology: Edam::Ontology.instance, bran
4747
self.ontology_term_fields ||= []
4848
self.ontology_term_fields << method.to_sym
4949

50+
define_method "#{links_method}=" do |links|
51+
send(links_method).reset
52+
current_links = send(links_method).to_a
53+
to_keep = []
54+
55+
links.reject(&:blank?).map do |link|
56+
idx = current_links.index { |l| l.term_uri == link.term_uri }
57+
if idx
58+
match = current_links.delete_at(idx)
59+
to_keep << match
60+
else
61+
to_keep << link
62+
end
63+
end
64+
65+
current_links.each(&:mark_for_destruction) # Now contains only redundant records
66+
67+
super(to_keep)
68+
end
69+
5070
# OntologyTerm objects
5171
define_method method do
5272
send(links_method).map(&:ontology_term).uniq

test/models/event_test.rb

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -775,4 +775,33 @@ class EventTest < ActiveSupport::TestCase
775775
assert_equal 'Goblet', bioschemas[:provider].first['name']
776776
assert_equal 'http://mygoblet.org', bioschemas[:provider].first['url']
777777
end
778+
779+
test 'does not destroy and recreate ontology term links' do
780+
e = events(:scraper_user_event)
781+
782+
# Via names
783+
assert_difference('OntologyTermLink.count', 2) do
784+
e.scientific_topic_names = %w[Proteins Chromosomes]
785+
e.save!
786+
assert_equal 2, e.scientific_topics.count
787+
end
788+
789+
ontology_term_links = e.ontology_term_links.to_a
790+
791+
assert_no_difference('OntologyTermLink.count') do
792+
e.scientific_topic_names = %w[Proteins Chromosomes]
793+
e.save!
794+
assert_equal 2, e.scientific_topics.count
795+
end
796+
797+
assert_equal ontology_term_links, e.reload.ontology_term_links.to_a
798+
799+
assert_no_difference('OntologyTermLink.count') do
800+
e.scientific_topic_names = %w[Proteins Biodiversity]
801+
e.save!
802+
assert_equal 2, e.scientific_topics.count
803+
end
804+
805+
assert_equal 1, (e.reload.ontology_term_links.to_a - ontology_term_links).length
806+
end
778807
end

0 commit comments

Comments
 (0)