diff --git a/app/models/data_file.rb b/app/models/data_file.rb index 72e6184129..51e7399bee 100644 --- a/app/models/data_file.rb +++ b/app/models/data_file.rb @@ -20,7 +20,7 @@ class DataFile < ApplicationRecord belongs_to :file_template has_many :extracted_samples, class_name: 'Sample', foreign_key: :originating_data_file_id - has_many :sample_resource_links, -> { where(resource_type: 'DataFile') }, class_name: 'SampleResourceLink', foreign_key: :resource_id + has_many :sample_resource_links, -> { where(resource_type: 'DataFile') }, foreign_key: :resource_id has_many :linked_samples, through: :sample_resource_links, source: :sample has_many :unzipped_files, class_name: 'DataFile', foreign_key: :zip_origin_id diff --git a/app/models/sop.rb b/app/models/sop.rb index 7e9b268605..4e6cb36b82 100644 --- a/app/models/sop.rb +++ b/app/models/sop.rb @@ -12,8 +12,9 @@ class Sop < ApplicationRecord #don't add a dependent=>:destroy, as the content_blob needs to remain to detect future duplicates has_one :content_blob, -> (r) { where('content_blobs.asset_version =? AND deleted=?', r.version, false) }, :as => :asset, :foreign_key => :asset_id - has_and_belongs_to_many :workflows + has_many :sample_resource_links, -> { where(resource_type: 'Sop') }, foreign_key: :resource_id + has_many :linked_samples, through: :sample_resource_links, source: :sample has_filter assay_type: Seek::Filtering::Filter.new( value_field: 'assays.assay_type_uri', @@ -50,4 +51,8 @@ def use_mime_type_for_avatar? true end + def related_samples + linked_samples + end + end diff --git a/test/unit/sop_test.rb b/test/unit/sop_test.rb index d6cd288430..d9570ab0c3 100644 --- a/test/unit/sop_test.rb +++ b/test/unit/sop_test.rb @@ -343,4 +343,27 @@ def test_project_for_sop_and_sop_version_match refute v3.can_change_visibility? end + test 'related samples' do + project = FactoryBot.create(:project) + + sample_type = FactoryBot.create(:sop_sample_type, project_ids: [project.id]) + sop_attr = FactoryBot.build(:sop_sample_attribute, title: 'sop 2', sample_type: sample_type) + sample_type.sample_attributes << sop_attr + sop = FactoryBot.create(:sop) + another_sop = FactoryBot.create(:sop) + sop_without_samples = FactoryBot.create(:sop) + + sample1 = Sample.new(sample_type: sample_type, project_ids: [project.id]) + sample1.update(data: { 'sop': sop.id }) + sample1.update(data: { 'sop 2': another_sop.id }) + sample1.save! + sample2 = Sample.new(sample_type: sample_type, project_ids: [project.id]) + sample2.update(data: { 'sop': another_sop.id }) + sample2.update(data: { 'sop 2': sop.id }) + sample2.save! + + assert_empty sop_without_samples.related_samples + assert_equal [sample1, sample2].sort_by(&:id), sop.related_samples.sort_by(&:id) + end + end