I have multiple tables with the same structure. They are all located in the same db with different names, storing different data. How can I set the schema in a fn to reduce boilerplate? Am I going about this the wrong way?
The code below results in the following error: (ArgumentError) cannot set attribute @ecto_schema_defined inside function/macro
defmodule NsMetrics.Name.Api do
use Ecto.Schema
import Ecto.Changeset
def set(db_name) do
schema db_name do
field(:date, :string)
field(:t1, :integer)
field(:t2, :integer)
field(:t3, :integer)
timestamps()
end
end
def changeset(line, attrs) do
line
|> cast(attrs, [:date, :t1, :t2, :t3])
|> validate_required([:date, :t1, :t2, :t3])
end
end
Thank you for the question! Even if I define a master schema, creating a schema module per table and defining the associations does not make sense. There could be hundreds of them and new ones will be added as time goes on⊠but they all share the same structure.
Then you should go for a custom Ecto.Type that is aware of the polymorphic pieces of data and properly branches on them to create the appropriate (different) Elixir structs.
If you can give us an example of a master and e.g. two âchildâ associations I believe we would be able to give you a head-start.
It would look something like this, if Im understanding correctly. So Im clear about my understanding of the following code. This will create a shared instance between 2 tables with the same fields⊠If that understanding is misapprehended please let me know!
EDIT: Id like to add here there are neither nor will there ever be fields that deviate from the same structure.
defmodule FieldsInCommon do
use Ecto.Schema
schema "fields_in_common" do
field(:date, :string)
field(:t1, :integer)
field(:t2, :integer)
field(:t3, :integer)
timestamps()
end
def changeset(line, attrs) do
line
|> cast(attrs, [:date, :t1, :t2, :t3])
|> validate_required([:date, :t1, :t2, :t3])
end
end
defmodule AdHocTable do
use Ecto.Schema
schema "ad_hoc_gen_table_name" do
many_to_many :fields, FieldsInCommon, join_through: "ad_hoc_gen_table_name_fields"
end
end
defmodule AdHocTable2 do
use Ecto.Schema
schema "ad_hoc_gen_table_name_2" do
many_to_many :fields, FieldsInCommon, join_through: "ad_hoc_gen_table_name_2_fields"
end
end
Still not quite clear. I donât see the value add of the second table.
Can you also give a few examples of actual data inside the DB? Just do a few select queries in psql and paste us the result here (with anonymized / edited values if you like)?
Its time series data from different sources. Putting them all in one table only stands to make handling the data arduous. They will all look the same as below.
ad_hoc_* there is no table fields_in_common its just that all the tables share all the same fields in common⊠Your question leads me to believe Im using it wrong⊠? Am I missing it?
Thank you for working with me!
Im looking over the Ecto.Type docs to try to anticipate your solutionâŠ