Search code examples
elixirphoenix-frameworkecto

Virtual models in ecto


Is there a way we can define a virtual model in ecto. Which don't have migration file and don't persist in the data base. I didn't find any documentation related to that in Ecto docs. I need this to test some functions in the iex. To test with models separate from the rest of the app.

I found embedded schema which contain fields that don't persist in the database but nothing related to the models.

Any help will be much appreciated.


Solution

  • Embedded schema is just fine.

    defmodule Test.Model do
      @moduledoc ~S"""
      The dummy test model that is not stored in the database.
      """
      use Ecto.Schema
      import Ecto.Changeset
    
      @type t :: Ecto.Schema.t
    
      @fields ~w|foo bar baz|a
      @primary_key false
    
      embedded_schema do
        field :foo, :string
        field :bar, :integer
        field :baz, :float
      end
    
      def new(data) when is_map(data) do
        %__MODULE__{}
        |> cast(data, @fields)
        |> validate_required(~w|foo|a)
        |> apply_changes()
      end
    end
    

    Once defined, it might be used as the normal schema.