Example of setting a has_one relationship

I would appreciate an example of setting up a has_one relationship. I have the following resources:
App.Api.Item
App.Api.Variant
App.Api.Item
App.Api.Variant
Each resource has an attribute uuid_primary_key :id. I want to establish a 1:1 relationship between the two resources. So, I add the following to App.Api.Item:
relationships do
has_one :variant, App.Api.Variant
end
relationships do
has_one :variant, App.Api.Variant
end
I get the following errors/warnings:
warning: invalid association `variant` in schema App.Api.Item: associated schema App.Api.Variant does not have field `item_id`
lib/app/api/resources/item.ex:1: App.Api.Item (module)

** (EXIT from #PID<0.96.0>) an exception was raised:
** (Spark.Error.DslError) [App.Api.Item]
relationships -> variant:
Relationship `variant` expects destination field `item_id` to be defined on App.Api.Variant
warning: invalid association `variant` in schema App.Api.Item: associated schema App.Api.Variant does not have field `item_id`
lib/app/api/resources/item.ex:1: App.Api.Item (module)

** (EXIT from #PID<0.96.0>) an exception was raised:
** (Spark.Error.DslError) [App.Api.Item]
relationships -> variant:
Relationship `variant` expects destination field `item_id` to be defined on App.Api.Variant
Do I need to define an attribute :item_id in resource App.Api.Variant? If so, what type would it be? Or am I on the wrong path?
7 Replies
waseigo
waseigoOP3y ago
Yes, I need to also define the following in App.Api.Variant:
attribute :item_id, :uuid
attribute :item_id, :uuid
Jmanda
Jmanda3y ago
I think in App.Api.Variant you have to define a belongs_to as supposed to adding attribute :item_id, :uuid, so something like:
relationships do
belongs_to :item, App.Api.Item
end
relationships do
belongs_to :item, App.Api.Item
end
ZachDaniel
ZachDaniel3y ago
Yeah defining the relationship is the more idiomatic way.
waseigo
waseigoOP3y ago
Thank you @Jmanda! And is there a way to recursively Api.load! all relationships, aggregates and calculations on a record that belongs_to records that belongs_to other records?
Jmanda
Jmanda3y ago
You can take a look at https://ash-hq.org/docs/module/ash/latest/ash-query#function-load-2 for loading nested relationships
Ash HQ
Module: Ash.Query
View the documentation for Ash.Query on Ash HQ.
waseigo
waseigoOP3y ago
Thanks, I do that now already, I was wondering if there's a function to load everything that's nested.
ZachDaniel
ZachDaniel3y ago
That’s not realistic really because you’d typically have “cycles” I.e a relationship back to the parent.

Did you find this page helpful?