Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions lib/has_ontology_terms.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,26 @@ def has_ontology_terms(association_name, ontology: Edam::Ontology.instance, bran
self.ontology_term_fields ||= []
self.ontology_term_fields << method.to_sym

define_method "#{links_method}=" do |links|
send(links_method).reset
current_links = send(links_method).to_a
Comment thread
fbacall marked this conversation as resolved.
to_keep = []

links.reject(&:blank?).map do |link|
idx = current_links.index { |l| l.term_uri == link.term_uri }
if idx
match = current_links.delete_at(idx)
to_keep << match
else
to_keep << link
end
end

current_links.each(&:mark_for_destruction) # Now contains only redundant records
Comment thread
fbacall marked this conversation as resolved.

super(to_keep)
end

# OntologyTerm objects
define_method method do
send(links_method).map(&:ontology_term).uniq
Expand Down
29 changes: 29 additions & 0 deletions test/models/event_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -775,4 +775,33 @@ class EventTest < ActiveSupport::TestCase
assert_equal 'Goblet', bioschemas[:provider].first['name']
assert_equal 'http://mygoblet.org', bioschemas[:provider].first['url']
end

test 'does not destroy and recreate ontology term links' do
e = events(:scraper_user_event)

# Via names
assert_difference('OntologyTermLink.count', 2) do
e.scientific_topic_names = %w[Proteins Chromosomes]
e.save!
assert_equal 2, e.scientific_topics.count
end

ontology_term_links = e.ontology_term_links.to_a

assert_no_difference('OntologyTermLink.count') do
e.scientific_topic_names = %w[Proteins Chromosomes]
e.save!
assert_equal 2, e.scientific_topics.count
end

assert_equal ontology_term_links, e.reload.ontology_term_links.to_a

Comment on lines +795 to +798

Copilot AI Mar 31, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This assertion compares arrays of ActiveRecord objects with an implicit ordering from the database. To avoid flaky tests across DB adapters or query plans, compare sorted IDs (or otherwise normalize ordering) rather than relying on to_a returning a stable order.

Copilot uses AI. Check for mistakes.
assert_no_difference('OntologyTermLink.count') do
e.scientific_topic_names = %w[Proteins Biodiversity]
e.save!
assert_equal 2, e.scientific_topics.count
end

assert_equal 1, (e.reload.ontology_term_links.to_a - ontology_term_links).length
end
end
Loading