Rbtz. CredoChecks. Warning. PreferGetFieldOnChangeset
(rbtz_credo_checks v0.3.0)
Copy Markdown
View Source
Basics
This check is disabled by default.
Learn how to enable it via .credo.exs.
This check has a base priority of normal and works with any version of Elixir.
Explanation
Encourages reading schema fields off an Ecto.Changeset via
Ecto.Changeset.get_field/2 rather than direct struct access
(changeset.changes.field, changeset.data.field) or Access
(changeset[:field]).
get_field/2 returns the post-cast value: it transparently picks the
change if one is present, falls back to the original data otherwise,
and respects embeds. Reaching into :data or :changes by hand only
sees one layer and easily reads a stale value when both exist.
changeset[:key] is a friendlier shortcut for the same direct access
and shares the pitfall.
Reads of the %Ecto.Changeset{} struct's own fields
(changeset.valid?, changeset.data, changeset.errors,
changeset.action, etc.) are not flagged — those are legitimate
uses of the struct's public API, not schema-field access.
To limit false positives, the check only runs against files that
import or alias Ecto.Changeset somewhere in the source — this
keeps it from flagging unrelated variables that happen to be named
changeset (e.g. struct fields, helper params).
Bad
name = changeset.changes.name
email = changeset.data.email
age = changeset[:age]Good
name = Ecto.Changeset.get_field(changeset, :name)
email = Ecto.Changeset.get_field(changeset, :email)
age = Ecto.Changeset.get_field(changeset, :age)Check-Specific Parameters
There are no specific parameters for this check.
General Parameters
Like with all checks, general params can be applied.
Parameters can be configured via the .credo.exs config file.