Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a changeset in phoenix elixir

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.

like image 607
Murtza Avatar asked Oct 17 '15 11:10

Murtza


People also ask

What is a changeset in git?

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.

What is ecto elixir?

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.


1 Answers

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.

like image 171
Gazler Avatar answered Oct 02 '22 10:10

Gazler