ChangesetHelpers (Changeset Helpers v0.2.0) View Source

Provides a set of helpers to work with Changesets.

Link to this section Summary

Functions

Returns the nested association in a changeset. This function will first look into the changes and then fails back on data wrapped in a changeset.

This function allows checking if a given field is different between two changesets.

Puts the given nested association in the changeset through a given list of field names.

Link to this section Functions

Link to this function

change_assoc(struct_or_changeset, keys, changes \\ %{})

View Source

Returns the nested association in a changeset. This function will first look into the changes and then fails back on data wrapped in a changeset.

Changes may be added to the given changeset through the third argument.

A tuple is returned containing the original changeset and the changeset of the association.

{account_changeset, address_changeset} =
  change_assoc(account_changeset, [:user, :user_config, :address], %{street: "Foo street"})
Link to this function

diff_field(changeset1, changeset2, keys)

View Source

This function allows checking if a given field is different between two changesets.

{street_changed, street1, street2} =
  diff_field(account_changeset, new_account_changeset, [:user, :user_config, :address, :street])
Link to this function

put_assoc(changeset, keys, value)

View Source

Puts the given nested association in the changeset through a given list of field names.

ChangesetHelpers.put_assoc(account_changeset, [:user, :config, :address], address_changeset)

Instead of giving a Changeset or a schema as the third argument, a function may also be given in order to modify the nested changeset in one go.

ChangesetHelpers.put_assoc(account_changeset, [:user, :articles],
  &(Enum.concat(&1, [%Article{} |> Ecto.Changeset.change()])))

In the code above, we add a new empty Article to the articles association (typically done when we want to add a new article to a form).