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.
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.