belongs_to does not add _id attributes do resource
The resource with attributes and relationships
does not have the attributes plano_id and pessoa_id.
If I try to insert a record, the insert command does not have the foreign keys:
15 Replies
how are you inserting?
you either need to set the foreign keys as writeable, or use manage_relationship to set them
and you should make them not null if they shouldn't be null
allow_nil?: false
I'm guessing you need to set this https://ash-hq.org/docs/dsl/ash-resource#relationships-belongs_to-attribute_writable- to true, otherwise it won't accept the ids.
I don't know if I'm using it correct.
I tried this:
and this
The define_attribute? is true by default, as it is explained in the docs. I thought I could use the belongs_to relation like I use it with Ecto.
Yes but attribute_writable is false by default. Meaning you would need to add it as an argument and set it yourself inside a change
How do I insert in a table and in its relation when getting information from a form?
I think you just need to add
attribute_writable? true
to your relationship definition
Then the code you posted should workYes, I tried that and it works. Thanks. Is this the right thing to do to insert a resource and its relation at once?
I'm not sure what the exact reason is for this default, but I would guess it is because adding a relationship often has a special use case and this could potentially encourage creating your own action for it. But if the ids always have to be set when creating the resource I think this is fine.
It always depends on what you are doing but if everything you do is just a create or update you lose a lot of context
I have some forms that collect information about one resource and its "children" (as post and comments), than I have to insert in the database the resource (post) and all its children (comments) at once (in the same db transaction). Is Ash able to do it? How?
You can use the
manage_relationship
change to accomplish thisJust a note: the doc (https://ash-hq.org/docs/dsl/ash-resource#relationships-belongs_to) say that belongs_to "creates a field on the resource with the corresponding name and type, unless define_attribute?: false is provided". It makes me think that, by default, belongs_to takes care of all the configuration.
https://discord.com/channels/711271361523351632/1155459759743438899 this should give you an idea on how to do it
I'll do that. Thanks.
It does add the attribute, but it configures the attribute with
attribute_writeable? false
by defaultAlright. Thanks.