3
votes

I'm trying to link two tables on a SHA1 rather than doing a find for the SHA1 across tables, and linking the via id.

My models are

class Dataset < ActiveRecord::Base
   belongs_to :dataset_hash
end

class DatasetHash < ActiveRecord::Base
   has_many :datasets
end

I tried linking using

  has_many :datasets, :finder_sql => 'Select datasets.* FROM datasets LEFT JOIN dataset_hashes ON datasets.dataset_hash=dataset_hashes.hash WHERE dataset_hashes.hash=#{dataset.dataset_hash}'

but I just get an error of

DatasetHash(#...) expected, got String(#...)

1
Have you had any luck using the :foreign_key option instead?tadman
from my understanding, foreign_key only lets me define a one-way relationship (unless I am not understanding it correctly), so with foreign_key I could say first_table.id maps to second_table.other_field by belongs_to first_table, :foreign_key => other_field. I don't see how I can define that across two non-id fieldspedalpete
It may be more convenient in your case to use a non-integer primary key.tadman

1 Answers

2
votes

You can use :foreign_key and :primary_key available in belongs_to and has_many:

class Dataset < ActiveRecord::Base
   belongs_to :dataset_hash, :primary_key => "dataset_hash", :foreign_key => "hash"
end

class DatasetHash < ActiveRecord::Base
   has_many :datasets, :primary_key => "hash", :foreign_key => "dataset_hash"
end