Reputation: 665
I'm rewriting an old PHP application and have to migrate the database. It has a join table harddisks_imagecapturing:
id manuscripts_id harddisk_id
-------------------------------
1 206 18
2 206 17
3 206 16
Table imagecapturing:
id harddisk_id library signature
-------------------------------
1 16 "foo" "MS352"
2 17 "bar" "AB67"
3 18 "baz" "WQ62"
Table harddisks:
id harddisk_name capacity
-------------------------------
16 "Seagate" 2000
17 "Seagate" 2000
18 "Seagate" 4000
The problem is, that I don't have an manuscript_id in the table imagecapturing instead a signature that is unique and could be used as a "helper table" to reference from manuscript table.
Table manuscripts:
id signature
---------------
206 "MS352"
How can I make the Rails associations right to retrieve the data into a table with the columns:
signature, library, harddisk_name, capacity
? I suppose one had to use the manuscript_id from harddisks_imagecapturing table to get the signature from the manuscript table.
class Imagecapturing < ApplicationRecord
self.table_name = 'imagecapturing'
belongs_to :harddisk
end
class HarddisksImagecapturing < ApplicationRecord
self.table_name = 'harddisks_imagecapturing'
belongs_to :harddisk
belongs_to :imagecapturing
end
class Harddisk < ApplicationRecord
has_many :manuscripts_harddisks
has_many :manuscripts, through: :manuscripts_harddisks
default_scope { order(kaufdatum: :desc) }
# Harddisk.order('id ASC').reorder('kaufdatum DESC')
end
class Manuscript < ApplicationRecord
end
Upvotes: 0
Views: 27
Reputation: 3475
You can specify which column(s) to use as the primary_key
and foreign_key
for associations. http://guides.rubyonrails.org/association_basics.html#options-for-belongs-to
class Manuscript < ApplicationRecord
belongs_to :imagecapturing, foreign_key: "signature", primary_key: "signature"
end
Alternatively, like you mentioned, you could navigate through your harddisks_imagecapturing
table as well.
Upvotes: 1