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 1 to 10

josevalim

josevalim

Creator of Elixir

If you don’t need to insert it, just validate it exists, you can let the database take care of it for you:

schema "countries" do
   field :code
   field :language
   field :text
   timestamps
end

def changeset(struct, params \\ %{}) do
  struct
  |> cast(params, [:text, :code, :language])
  |> validate_required([:code, :language, :text])
  |> foreign_key_constraint(:code, name: :name_of_the_code_foreign_key)
  |> foreign_key_constraint(:language, name: :name_of_the_language_foreign_key)
end

Then you can query your database to find the name of the foreign keys. If you are not sure the foreign key exists, then you can try to insert a country with a code that certainly does not exist and Ecto will error, telling you which foreign key name that failed, or succeed, which means you have no primary keys and therefore you should add one.

kostonstyle

kostonstyle OP

First of all, thanks for your answer.

Do I need anymore?

|> cast_assoc(:code)
|> cast_assoc(:language)

or just:

def changeset(struct, params \\ %{}) do
  struct
  |> cast(params, [:text])
  |> validate_required([:code, :language, :text])
  |> foreign_key_constraint(:code, name: :name_of_the_code_foreign_key)
  |> foreign_key_constraint(:language, name: :name_of_the_language_foreign_key)
end

Thanks

josevalim

josevalim

Creator of Elixir

Sorry, you are right. You don’t need cast_assoc but make sure you pass both :code and :language to cast. I will edit my previous answer for clarify.

kostonstyle

kostonstyle OP

Thanks jose.

josevalim

josevalim

Creator of Elixir

Did it work? :smiley:

kostonstyle

kostonstyle OP

Sorry.
I changed my schema to:

schema "countries" do

    field :code, :string
    field :language, :string
    field :text, :string

    timestamps

  end

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

	  model
	  |> cast(params, [:code, :language, :text])
	  |> validate_required([:code, :language, :text])
	  |> foreign_key_constraint(:code, name: :alpha2)
      |> foreign_key_constraint(:language, name: :code)

  end

as output

iex(11)> v = %{code: "LK", language: "ZZ", text: "Schweiz"}
%{code: "LK", language: "ZZ", text: "Schweiz"}
iex(12)> c = Country.changeset(%Country{}, v)              
#Ecto.Changeset<action: nil,
 changes: %{code: "LK", language: "ZZ", text: "Schweiz"}, errors: [],
 data: #Busiket.Country<>, valid?: true>

It should complain, a country with code LK does not exists!

Thanks

kostonstyle

kostonstyle OP

@josevalim I found the error, it is on migration file, since I rename the column:

create table(:countries) do
  add :coun, references(:countries_code, column: :alpha2, type: :string)
  add :lang, references(:languages_code, column: :code, type: :string)
  add :text, :string

  timestamps
		end

create unique_index(:countries, [:coun, :lang])

I rename the column from coun to code and from lang to language.
Now how to add references to the new name of columns?

kostonstyle

kostonstyle OP

Delete and create the countries database with:

  def change do

    drop table(:countries)

    create table(:countries) do
      add :code, references(:countries_code, column: :alpha2, type: :string)
      add :language, references(:languages_code, column: :code, type: :string)
      add :text, :string

      timestamps
    end

    create unique_index(:countries, [:code, :language])

  end

and tried with:

iex(2)> v = %{code: "LK", language: "ZZ", text: "Schweiz"}
%{code: "LK", language: "ZZ", text: "Schweiz"}
iex(3)> c = Country.changeset(%Country{}, v)  
#Ecto.Changeset<action: nil,
 changes: %{code: "LK", language: "ZZ", text: "Schweiz"}, errors: [],
 data: #Busiket.Country<>, valid?: true>

The compiler should complain.

josevalim

josevalim

Creator of Elixir

If you are using “references”, one is automatically added for you. Please
check the answer in my first post, I think you did not add the new fields
to the “cast” call in your changeset function (because I forgot to do so as
well in my original reply).

kostonstyle

kostonstyle OP

Hi jose
I tried again as you metioned and it does not work.

The schema and changeset function:

  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, name: :iso)
    |> foreign_key_constraint(:iso_language, name: :iso)

  end

and migration:

def change do

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

create unique_index(:countries, [:iso_country, :iso_language])

When I look at the pgAdmin console, the migration did the right job:

as you can see on the picture, the constraints on countries table is available.

I test as follow:

iex(4)> a = %{iso_country: "YY", iso_language: "DE", name: "Schweiz"}
%{iso_country: "YY", iso_language: "DE", name: "Schweiz"}
iex(5)> Country.changeset(%Country{}, a)
#Ecto.Changeset<action: nil,
 changes: %{iso_country: "YY", iso_language: "DE", name: "Schweiz"}, errors: [],
 data: #Busiket.Country<>, valid?: true>

The country with iso YY does not exists on countries_code db:

What am I doing wrong?

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
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
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
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
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

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
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
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
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

Latest on Elixir Forum

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews