Ecto.Changeset.prepare_changes
prepare_changes
, go back to Ecto.Changeset module for more information.
Specs
Provides a function executed by the repository on insert/update/delete.
If the changeset given to the repository is valid, the function given to
prepare_changes/2
will be called with the changeset and must return a
changeset, allowing developers to do final adjustments to the changeset or
to issue data consistency commands. The repository itself can be accessed
inside the function under the repo
field in the changeset. If the
changeset given to the repository is invalid, the function will not be
invoked.
The given function is guaranteed to run inside the same transaction as the changeset operation for databases that do support transactions.
Example
A common use case is updating a counter cache, in this case updating a post's comment count when a comment is created:
def create_comment(comment, params) do
comment
|> cast(params, [:body, :post_id])
|> prepare_changes(fn changeset ->
if post_id = get_change(changeset, :post_id) do
query = from Post, where: [id: ^post_id]
changeset.repo.update_all(query, inc: [comment_count: 1])
end
changeset
end)
end
We retrieve the repo from the comment changeset itself and use update_all to update the counter cache in one query. Finally, the original changeset must be returned.