I have the following diagram:
schema "countries" do
belongs_to :code, CountryCode, references: :alpha2
belongs_to :language, LanguageCode, references: :code
field :text, :string
timestamps
end
My question is: how to write a change set function for the circuit above?
I tried:
def changeset(model, params \\ %{}) do
model
|> cast(params, [:text])
|> cast_assoc(:code)
|> cast_assoc(:language)
|> validate_required([:code, :language, :text])
end
And I have an error message:
errors: [language: {"is invalid", [type: :map]},
code: {"is invalid", [type: :map]}], data:
UPDATE
I rewrite the change set function:
def changeset(model, params \\ %{}) do
model
|> cast(params, [:code_id, :language_id, :text])
|> cast_assoc(:code)
|> cast_assoc(:language)
|> validate_required([:code, :language, :text])
end
and I have:
errors: [language: {"is invalid", [type: :map]},
code: {"is invalid", [type: :map]}], data:
Sorry, here is a diagram from mine LanguageCode:
schema "languages_code" do
has_one :code, Country, foreign_key: :lang
field :text, :string
timestamps
end
UPDATE
I am testing it again in the shell:
iex(4)> v = %{code: %{code: "CH"}, language: %{alpha2: "DE"}, text: "Schweiz"}
%{code: %{code: "CH"}, language: %{alpha2: "DE"}, text: "Schweiz"}
iex(5)> c = Country.changeset(%Country{}, v)
changes: %{code:
errors: [alpha2: {"can't be blank", []}, alpha3: {"can't be blank", []}],
data:
language:
errors: [code: {"can't be blank", []}, text: {"can't be blank", []}],
data:
data:
I forgot to mention that the data in the language_code table is already available:
