kostonstyle

kostonstyle

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

Showing Posts 11 to 20

josevalim

josevalim

Creator of Elixir

Constraints are only tested after you do a repository operation, such as Repo.insert, since it is the database reporting what is wrong (rather than we testing it).

kostonstyle

kostonstyle OP

So, I have to do Repo.insert to get to know if there is a constraint error or not?

josevalim

josevalim

Creator of Elixir

Yes, that’s by definition how constraints in Ecto work. They rely on the
database as the da abase is the only one who can effectively say if that
relationship exists or not.

kostonstyle

kostonstyle OP

My last question(hopefully :slight_smile: ), when I tried to insert into db, I’ve got an exception:

iex(5)> e = Repo.insert(c)
[debug] QUERY ERROR db=16.0ms
INSERT INTO "countries" ("iso_country","iso_language","name","inserted_at","updated_at") VALUES ($1,$2,$3,$4,$5) RETURNING "id" ["YY", "DE", "Schweiz", {{2016, 11, 24}, {13, 28, 8, 0}}, {{2016, 11, 24}, {13, 28, 8, 0}}]
** (Ecto.ConstraintError) constraint error when attempting to insert struct:

If you would like to convert this constraint into an error, please
call foreign_key_constraint/3 in your changeset and define the proper
constraint name. The changeset defined the following constraints:

How to get a message instead raised exception?
In doc Ecto.Repo — Ecto v3.14.0 it says, I should get a tuple.

Thanks

josevalim

josevalim

Creator of Elixir

Can you post the full message? The error message is telling exactly what you need to do. You need to pass the :name option to foreign_key_constraint/3 with the foreign key name that is failing.

kostonstyle

kostonstyle OP

I’ve found the solution:

  def changeset(struct, params \\ %{}) do

    struct
    |> cast(params, [:iso_country, :iso_language, :name])
    |> validate_required([:iso_country, :iso_language, :name])
    |> foreign_key_constraint(:iso_country)
    |> foreign_key_constraint(:iso_language)

  end

It works as expected.
At last, what is the :name options for, that I can pass?

kostonstyle

kostonstyle OP

with the name option, I’ve got error as I mentioned above.

kostonstyle

kostonstyle OP

So I will post the final code, that works.

  schema "countries" do

    field :iso_country, :string
    field :iso_language, :string
    field :name, :string

    timestamps

  end

  def changeset(struct, params \\ %{}) do

    struct
    |> cast(params, [:iso_country, :iso_language, :name])
    |> validate_required([:iso_country, :iso_language, :name])
    |> foreign_key_constraint(:iso_country)
    |> foreign_key_constraint(:iso_language)

  end

Look at the function foreign_key_constraint, I do not pass the name option parameter and it works. Why? What is the use of the name option parameter?

josevalim

josevalim

Creator of Elixir

The name option would be given to the foreign_key_constraint function. If it works without passing the :name option, it means Ecto is guessing the proper name for you.

kostonstyle

kostonstyle OP

So, when I what to pass the :name option, how do I have to write?
The migration of countries looks as follow:

create table(:countries) do

      add :iso_country, references(:countries_code, column: :iso, type: :string)
      add :iso_language, references(:languages_code, column: :iso, type: :string)
      add :name, :string

      timestamps
    end

Thanks

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews