The first will cast and validate the external data with its own structure which you then transform and write to the database. One alternative solution is to break the "Database Ecto schema Forms / API" mapping in two parts. If the Profile schema is used for both reading and writing data, it may end-up in an awkward place where it is not useful for any, as it contains fields that map just to one or the other operation. It is not hard to see how we are polluting our Profile schema with UI requirements by adding fields such first_name and last_name. One of such schemas would be: defmodule Profile do use Ecto.Schema schema "profiles" do field :name field :first_name, :string, virtual : true field :last_name, :string, virtual : true. One approach would be to have two schemas, Account and Profile, with virtual fields such as first_name and last_name, and use associations along side nested forms to tie the schemas to your UI. Given the requirements above, how would we implement the Sign Up feature in the backend? Furthermore, you know it would be useful to break the "Sign Up" information across two tables, the "accounts" and "profiles" tables. Although your client is decided on presenting both fields, they are a UI concern, and you don't want the UI to dictate the shape of your data. You know there are a couple problems with this approach.įirst of all, not everyone has a first and last name. Imagine you are working with a client that wants the "Sign Up" form to contain the fields "First name", "Last name" along side "E-mail" and other information. We put emphasis on any because it is a common misconception to think Ecto schemas map only to your database tables.įor instance, when you write a web application using Phoenix and you use Ecto to receive external changes and apply such changes to your database, we have this mapping: Database Ecto schema Forms / APIĪlthough there is a single Ecto schema mapping to both your database and your API, in many situations it is better to break this mapping in two. Schemas are mappersĪn Ecto schema is used to map any data source into an Elixir struct. Maybe one for your database, another for your forms. Maybe one for reading data, another for writing. As we will see, sometimes the best solution is not to completely avoid schemas, but break a large schema into smaller ones. We will take a look at the role schemas play when validating and casting data through changesets. Settings View Source Data mapping and validation
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |