Does anyone have any hard and fast rules for when they use the assoc functions vs the assoc_id field on the schema?
Here’s a hypothetical scenario:
I’ve got a Post schema which has a belongs_to of type User. Since I’m never going to be creating a User at the same time as a Post, is there any benefit to using the *_assoc functions, or should I just set the user_id explicitly in the changeset?
Thoughts?
1 Like
I think it really depends on whether you have a requirement to save things at the same time (by working with the full association) or not.
I find it more helpful to represent dependencies for relationships that need additional information. This is a silly example, but imagine you have an Item
, Recipe
, and RecipeItem
schema, where RecipeItem
contains both the FKs to Item
and Recipe
but also an amount
and units
column. Then let’s say we want to store/ dump a JSON full of recipes:
{
"name": "Mashed Potatoes",
"recipe_items": [
{"name": "Potato", "amount": 2}
{"name": "Milk", "amount": 1, "units": "spoons"}
]
}
In this scenario, it’s easier to visualize dependencies and work with the whole thing. if you are not doing that, I don’t really see any advantages, only downsides - like exposing information that you can accidentally change.
Now, If you control the information and don’t need to cast the association, you might as well just use put_assoc
or put_change
to set either the whole association or the FK (the golden rule is that you cast stuff that is external to the app).