Hi there!
I have an Ecto Changeset, that uses validate_inclusion
against quite a few lists of values (country codes, packaging types, categories, etc). Some of these lists are in the database. Requesting the db from the changeset would be inefficient in case of batch inserts/updates.
I have been preloading these lists and sending to the changeset, so it would be one call to db on each batch of updates/inserts, instead of one per each row. Plus it feels more “pure” in terms of functions.
Now it becomes cumbersome. I’m considering to switch to calls directly from the changeset and using cachex
as a proxy.
Current code:
def create_batch(list_of_params) do
lists_of_values = App.Lists.get_lists()
Enum.map(list_of_params, fn params ->
changeset(struct, params, lists_of_values) |> Repo.insert
end
end
def changeset(struct, params, lists_of_values)
struct
...
|> validate_inclusion(:field, lists_of_values[:package_codes])
end
Potential refactoring
def create_batch(list_of_params) do
Enum.map(list_of_params, fn params ->
changeset(struct, params) |> Repo.insert
end
end
def changeset(struct, params)
struct
...
|> validate_inclusion(:field, App.CachedLists.get(:package_codes))
end
I have some concerns about potential downsides. Would appreciate an advice.
- Keep sending lists of values to changeset
- Request lists of values directly from changeset
0 voters