Hi all
I have following schemas
schema "languages_code" do
field :code, :string
field :text, :string
timestamps
end
and another schema that will be associated with languages_code schema:
schema "countries" do
belongs_to :code, CountryCode, references: :alpha2
belongs_to :language, LanguageCode, references: :code
field :text, :string
timestamps
end
def changeset(model, params \\ %{}) do
model
|> cast(params, [:text])
|> cast_assoc(:code)
|> cast_assoc(:language)
|> validate_required([:code, :language, :text])
end
Then I test it as follow:
iex(1)> alias Busiket.Country
Busiket.Country
iex(2)> v = %{code: "CH", language: "DE", text: "Schweiz"}
%{code: "CH", language: "DE", text: "Schweiz"}
iex(3)> c = Country.changeset(%Country{}, v)
#Ecto.Changeset<action: nil, changes: %{text: "Schweiz"},
errors: [language: {"is invalid", [type: :map]},
code: {"is invalid", [type: :map]}], data: #Busiket.Country<>, valid?: false>
iex(4)>
What is wrong with association?
Update
I tried as follow:
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)
#Ecto.Changeset<action: nil,
changes: %{code: #Ecto.Changeset<action: :insert, changes: %{},
errors: [alpha2: {"can't be blank", []}, alpha3: {"can't be blank", []}],
data: #Busiket.CountryCode<>, valid?: false>,
language: #Ecto.Changeset<action: :insert, changes: %{},
errors: [code: {"can't be blank", []}, text: {"can't be blank", []}],
data: #Busiket.LanguageCode<>, valid?: false>, text: "Schweiz"}, errors: [],
data: #Busiket.Country<>, valid?: false>
I’ve forgot to mention, that the data on the language_code
table is already available:
I do not have to insert it, only to validate, if the value of the field code
of the country
is match to the table of language_code
.
Thanks