Using ecto to store user information

I am reprogramming the application that I originally wrote in Rails in Phoenix, in which users can create custom fields using the PostgreSQL JSONB record type. As an example, we have the following diagram (simplified representation):

Client

  • ID (int)
  • Client Type Identifier (int)
  • Name (string)
  • Information (jsonb)

Customer type

  • ID (int)
  • Name (string)

Custom field definition

  • ID (int)
  • Client Type Identifier (int)
  • Key (string)
  • Label (string)

In Rails, ActiveRecord magically converts JSONB to and from hash, which makes it very easy for me to use JSONB to store a custom set of custom fields.

, , , , , , JSONB.

, , Ecto, , ( ), , , , , ?

, , , .

, !

+4
2

, . JSONB, embeds_many, . (http://blog.plataformatec.com.br/2015/08/working-with-ecto-associations-and-embeds/), , .

, JSONB,

{
  "name":"Something",
  "address":"123 Fake St"
}

[
  {
    "field":"name",
    "value":"Something"
  },
  {
    "field":"address",
    "value":"123 Fake St"
  },
]

, , ( Ecto , ).

. :

defmodule UserManager.CustomField do
  use Ecto.Model

  embedded_schema do
    field :field
    field :value
  end

  @required_fields ~w(field value)
  @optional_fields ~w()

  @doc """
  Creates a changeset based on the `model` and `params`.

  If no params are provided, an invalid changeset is returned
  with no validation performed.
  """
  def changeset(model, params \\ :empty) do
    model |> cast(params, @required_fields, @optional_fields)
  end
end

defmodule UserManager.Client do
  # ...
  schema "clients" do
    # ...
    embeds_many :custom_fields, UserManager.CustomField
    # ...
  end
  # ...
end
+1

Postgrex JSON Readme, , .

0

Source: https://habr.com/ru/post/1608568/


All Articles