I'm having problem understanding the changeset
in model. What it does? Can we have more than one changeset in a single model? e.g. one for create and another for update.
Can someone elaborate in a simple way so it helps other folks coming to Phoenix.
Indivisible simply means that a changeset is one single value in the stack of changes that are being made on a codebase. For example, if you look at a commit, you can check what individual files were modified, what was the previous state of the codebase and after, which would make it adhere to what a changeset is.
Ecto is an official Elixir project providing a database wrapper and integrated query language. With Ecto we're able to create migrations, define schemas, insert and update records, and query them. Changesets. In order to insert, update or delete data from the database, Ecto. Repo.
From the documentation:
Changesets allow filtering, casting, validation and definition of constraints when manipulating models..
There is an example of working with changesets in the introductory documentation in the Ecto module. The functions change/2 and cast/4 are the usual entry points for creating changesets, while the remaining functions are useful for manipulating them.
Changesets are used for creating and modifying your models. A changeset is literally a struct that stores a set of changes (as well as the validation rules.) You pass a changeset to your Ecto Repo to persist the changes if they are valid.
The current master branch of Ecto removes an implicit conversion when passing a model to the Repo on update, which means using a changeset the only way to update a model.
From the changelog:
Given a model to Repo.update/2 has been deprecated as it is inneffective and error prone since changes cannot be tracked
In terms of having multiple changesets per model, the answer is certainly yes. A changeset is simply a function. You actually don't even need to put the changeset functions in your models, however that is a common place to put them.
If you require more fields when registering a user than you do updating a user then you can define aregister_changeset
and a create_changeset
with different required fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With