mathieuprog

mathieuprog

Changeset Helpers – Ease working with nested Changesets and associations

Anyone who had to deal with change-ing nested associations knows how strugglesome and tedious it can get.

This library provides for now three convenient functions.

  1. Nest a change into a changeset:
ChangesetHelpers.put_assoc(account_changeset, [:user, :config, :address], address_changeset)

A function may also be provided as third argument, which receives the nested changeset (or data wrapped by a new changeset) as argument and returns the modified changeset.

For example in the code below I change an empty entity and add it into the association (typically when you want to insert a new row of inputs in a form to add an entity into a collection of persisted entities):

ChangesetHelpers.put_assoc(account_changeset, [:user, :articles],
  &(Enum.concat(&1, [%Article{} |> Ecto.Changeset.change()])))
  1. Change a nested association:
{account_changeset, address_changeset} =
  ChangesetHelpers.change_assoc(account_changeset, [:user, :user_config, :address])
{account_changeset, address_changeset} =
  ChangesetHelpers.change_assoc(account_changeset, [:user, :user_config, :address], %{street: "Foo street"})

A tuple is returned containing the modified root changeset and the association changeset.

  1. Check whether a given field is different between two changesets:
{street_changed, street1, street2} =
  ChangesetHelpers.diff_field(account_changeset, new_account_changeset, [:user, :user_config, :address, :street])

It’s quite niche but I still wanted to share the work with you :grin:

https://github.com/mathieuprog/changeset_helpers

Most Liked

mathieuprog

mathieuprog

I added a changeset utility function raise_if_invalid_fields(changeset, fields).

For example:

changeset
|> validate_inclusion(:cardinal_direction, ["north", "east", "south", "west"])
|> raise_if_invalid_fields([:cardinal_direction])

As its name suggests, the function raises if one of the given fields was provided with an invalid value.

Motivation/use case:

Say you have a dropdown list from which a user may select a value (like a <select> element). If the change is not included in the list, what happened?
It’s either a bug in the application, or a script, a malicious user or bot that bypassed the form control inputs.

As the very first version of my application will definitely have bugs, I want to raise to make sure that I don’t miss such a bug (if it were a bug); because if I just add a changeset error, I will not be automatically alerted of the bug, and have to rely on the user to report such cases.

If scripts or bots are abusing my forms, I can just remove the function call and let the error in the changeset (you don’t want to let your application because of a user submit).

Just an idea. Any thoughts welcome:)

mathieuprog

mathieuprog

Added fetch_field(changeset, keys) and fetch_change(changeset, keys) (and their bang ! versions).

street = ChangesetHelpers.fetch_field!(account_changeset, [:user, :config, :address, :street])
mathieuprog

mathieuprog

Version 0.17 is released:

  • dropped raise_if_invalid_fields/2

  • added field_fails_validation?/3 and field_violates_constraint?/3

Use case: sometimes instead of returning changeset errors to the client, you want to return a specialized response for some of the errors that happened. This is especially useful for returning specialized GraphQL objects representing errors in some cases, instead of a set of generic changeset errors.

Example:

case Accounts.register_user(input) do
  # ...
  {:error, changeset} ->
    email_already_used? =
      ChangesetHelpers.field_fails_validation?(changeset, :email, :unsafe_unique)
      || ChangesetHelpers.field_violates_constraint?(changeset, :email, :unique)

    if email_already_used? do
      # ...
    else
      {:error, changeset}
    end
end

Where Next?

Popular in Announcing Top

msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
deadtrickster
I’ve just released stable versions of my Prometheus Elixir libs: Elixir client [docs]; Ecto collector [docs]; Plugs instrumenter/Export...
New
brainlid
LangChain is short for Language Chain. An LLM, or Large Language Model, is the “Language” part. This library makes it easier for Elixir a...
New
oltarasenko
Dear Elixir community, After a year of development, bug fixes, and improvements, we are proudly ready to share the release of Crawly 0.1...
New
MRdotB
I needed to reuse React components from my Chrome extension in my Phoenix/LiveView backend. I noticed that for Svelte/Vue, there are live...
New
RobertDober
Earmark is a pure-Elixir Markdown converter. It is intended to be used as a library (just call Earmark.as_html), but can also be used as...
239 12560 134
New
sbs
Only 650 LOC, wrote for fun :slight_smile: https://github.com/sunboshan/qrcode
New
aditya7iyengar
Rummage.Ecto and Rummage.Phoenix provide ways to perform Searching, Sorting and Pagination over Ecto queries and Phoenix collections. Fo...
New
fuelen
Hey folks! Want to present a toolkit for writing command-line user interfaces. It provides a convenient interface for colorizing text...
New
benlime
LiveMotion enables high performance animations declared on the server and run on the client. As a follow up to my previous thread A libr...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New

We're in Beta

About us Mission Statement