gordoneliel
AshJsonApi: Create relationship when creating resource
I have a resource, eg Post, where the post has many Authors. When creating a Post, there should be at least one (1) Author attached to the payload. I know the json api v1 spec does not really outline creating multiple resources at once, but I figured we should be able to regardless?
What I’ve tried so far:
- Passing the relationship in the relationships section of the body - This fails with stack
[error] GenServer #PID<0.767.0> terminating
** (FunctionClauseError) no function clause matching in anonymous fn/2 in AshJsonApi.Request.relationship_change_value/1
(ash_json_api 0.33.1) lib/ash_json_api/request.ex:668: anonymous fn(:error, {:ok, []}) in AshJsonApi.Request.relationship_change_value/1
(elixir 1.15.7) lib/enum.ex:4387: anonymous fn/3 in Enum.reduce/3
- Passing the relationship into the
Postattributes when creating - This does not work, throws an invalid body because theAuthorattribute is not an attribute on the resource but rather a relationship.
I combed through the relationships section of Ash and AshJsonApi but cant seem to find anything related to creating multiple related resources.
Marked As Solved
zachdaniel
You can simplify a bit if you do
belongs_to :post, Post do
attribute_writable? true
end
then they can provide the post_id directly as an input. Then
create :create do
accept [..., :post_id]
primary? true
end
And then use that one action in both. Since post_id is not nullable, you will always be prevented from creating a comment with no post, and the manage_relationship will set post_id automatically.
Also Liked
zachdaniel
Okay, I can see it now, yeah. It should be in the relationships, but the issue is that we are currently requiring id, which doesn’t make sense in all contexts. I’ve just pushed something to main to make those optional. Additionally, extra attributes have to go in the "meta" key of the relationship, i.e {type: "type", "meta" => {foo: "bar"}}. This is required by the spec, IIRC.
gordoneliel
I think that would work! The json api spec for v1 is a little weird with this, I wonder if the upcoming v1.2 spec makes it easier to do this








