Reputation: 293
I've found quite a few topics on ActiveRecord
has_many
relationships, but I haven't found exactly what I am looking for.
I've got two tables that each have the column xyz_id. This id is a corresponding ID in an API service I'm subscribed to.
I want to have a has_many
relationship through these corresponding ids in the corresponding columns on each table. Such that, if an item in table_1 has an xyz_id of "abcdefg", I can do something like table_1.relation
and it will return all elements in table_2 with a matching xyz_id. I could leverage ActiveRecord
throughout my code and utilize queries, but I think there has to be a better way. Any thoughts?
EDIT: I a word.
Upvotes: 1
Views: 239
Reputation: 17647
ActiveRecord lets you specify arbitrary fkeys when you define the relationship, like so:
class Assembly < ActiveRecord::Base
has_and_belongs_to_many :parts,
foreign_key: :xyz_id
end
class Part < ActiveRecord::Base
has_and_belongs_to_many :assemblies,
foreign_key: :xyz_id
end
Source: http://guides.rubyonrails.org/association_basics.html
Upvotes: 1