How do relationships with composite keys work?

I found this mention of composite keys in the docs:
has_many :composite_key_posts, MyApp.CompositeKeyPost do
destination_attribute :author_id
end
has_many :composite_key_posts, MyApp.CompositeKeyPost do
destination_attribute :author_id
end
Ideally I need something like:
belongs_to :widget, MyApp.Widget do
source_attribute: [:scope_key, :source_key]
destination_attribute: [:scope_key, :destination_key]
end
belongs_to :widget, MyApp.Widget do
source_attribute: [:scope_key, :source_key]
destination_attribute: [:scope_key, :destination_key]
end
A similar effect to have scope_key being a tenant.
7 Replies
ZachDaniel
ZachDanielβ€’2y ago
There isn’t a way to do that currently, without using manual relationships
Robert Graff
Robert GraffOPβ€’2y ago
Very edge use case. I have some easy alternative options that will work.
Dimitri
Dimitriβ€’15mo ago
While looking for an answer to this same question I ended up here. Hi btw! First message here πŸ™‚ I found out the destination_attribute still expects a single atom. Am i correct in assuming there hasn't been any change arround this subject and a manual relationship is still the way to go when one would be trying to write a belongs_to pointing to a table with a composit primary key?
ZachDaniel
ZachDanielβ€’15mo ago
πŸ‘‹ This forum area is archived, but happy to answer here πŸ˜„ You can achieve this kind of thing with the filter option
belongs_to :widget, MyApp.Widget do
filter expr(other_destination_field == parent(other_source_field))
end
belongs_to :widget, MyApp.Widget do
filter expr(other_destination_field == parent(other_source_field))
end
Robert Graff
Robert GraffOPβ€’15mo ago
That's correct
Dimitri
Dimitriβ€’15mo ago
Heya, thanks for respondin guys! I thought I'd keep it in one place and kind of missed its an actual archive πŸ˜… Im not quite sure tho how this would work in my case. As Im trying to set an actual foreign key based of of a primary key thats a composite of 2 fields. Your example just looks like a runtime query instead of being able to save a foreignkey (in postgres) 🧐 ?
ZachDaniel
ZachDanielβ€’15mo ago
Ah, okay so to have the migration generator do that you can configure the references block in the postgres DSL https://hexdocs.pm/ash_postgres/1.5.15/dsl-ashpostgres-datalayer.html#postgres-references-reference-match_with
reference :widget, match_with: [other_source_field: :other_destination_field]
reference :widget, match_with: [other_source_field: :other_destination_field]

Did you find this page helpful?