top | item 34339637

(no title)

Ankhers | 3 years ago

I'm not really following this. The only problem the author has is with the name `create_changeset`. It may not be obvious to someone just starting with Elixir and Ecto what that means, but it is a naming convention that most (all?) projects use. You should be able to get the hang of it fairly quickly.

This may just be the simplicity of the example they have, but they also have an `update_changeset`, which I think is an anti-pattern. You should be creating a different changeset for each operation that can be applied to a given schema. In the case of a user, you may be able to change a password, or an email address separately from being able to change a screen name or something. You should be creating separate changeset functions for each of those operations.

The author also puts a foot note at the end stating that they would usually create a `base_changeset` function that can be reused for common parts of a changeset. Please don't do this. Just create multiple reusable functions for each check. For example, you may create private functions in the schema for `validate_email`, `validate_password`, etc. These are the reusable pieces that you most likely want to have and can be used from within any changeset. Then you will be able to mix and match them as needed instead of trying to come up with a truly base changeset that applies to everything and still have a lot of validation rules duplicated between various changesets.

discuss

order

monooso|3 years ago

> ...they also have an `update_changeset`, which I think is an anti-pattern.

I disagree that it's an anti-pattern. I'm already making a distinction between a "create" and an "update" changeset, as these may have different validation rules.

Of course, some situations may warrant separate changesets for operations on individual fields (updating an email address, updating a password, etc.), but in practise I rarely find this to be useful.

> Please don't do this. Just create multiple reusable functions for each check.

It's worth noting that these aren't mutually exclusive approaches; we regularly use both on my current project.

Ankhers|3 years ago

I will agree that not every situation will require multiple kinds of updates. For those situations an `update_changeset` may be considered okay. I now realize how definite my wording sounds. But I just meant that if you have multiple update operations, that should be exposed as multiple changeset functions. If you have multiple update operations but a single update_changeset function, it is possible to send the server data you did not intend to be sent together and now you are changing things that were not originally meant to be changed together. This has happened in previous projects I have worked on and now prefer the be explicit with multiple changeset functions.