Yura Zhivaga
Yura Zhivaga

Reputation: 108

Phoenix, function in model schema

How to add function in schema? I want to create function for dynamically add fields to model schema. Example:

  def func do
    # .. loop to create dynamic fields
    field :street, :string
  end

  schema "objects" do
    func
  end

... Error:

** (CompileError) web/models/objects.ex:12: undefined function func/0

Upvotes: 0

Views: 711

Answers (2)

Sbbs
Sbbs

Reputation: 1680

Another solution:

  @some_attributes ["attr_1", "attr_2"]

  schema "your_table" do
    for field <- @some_attributes do
      field field, :boolean, default: false
    end
  end

Upvotes: 0

Dogbert
Dogbert

Reputation: 222368

func needs to be in a separate module since you want to call it from the body of this module. func also needs to be a macro that returns a quoted AST containing the field calls so that field is able to put the fields in the correct module since field too is a macro. You're looking for something like this:

defmodule MyApp.Post.Helper do
  defmacro func do
    quote do
      field :foo, :string
    end
  end
end

defmodule MyApp.Post do
  use MyApp.Web, :model
  import MyApp.Post.Helper

  schema "posts" do
    func()
  end
end

Test:

iex(1)> %Post{}
%MyApp.Post{__meta__: #Ecto.Schema.Metadata<:built, "posts">, foo: nil, id: nil}

Upvotes: 5

Related Questions