Hi guys, I do have a problem regarding ecto queries. As you can see below, you’ll find that I’m trying to link currencies table to exchange_rates table. But unfortunately, it doesn’t work as error is trying to find “from_currency_id ” column on exchange_rates table on which is named “from_currency_id”. How can I properly link these two tables
This is my currencies table definition:
use Ecto.Migration
def change do
create table(:currencies) do
add :name, :string
add :symbol, :string
timestamps()
end
end
This is my exchange_rates table definition:
use Ecto.Migration
def change do
create table(:exchange_rates) do
add :rate, :decimal
add :from_currency_id, references(:currencies, on_delete: :nothing)
add :to_currency_id, references(:currencies, on_delete: :nothing)
timestamps()
end
create index(:exchange_rates, [:from_currency_id])
create index(:exchange_rates, [:to_currency_id])
end
This is my currencies table changeset module:
schema "currencies" do
field :name, :string
field :symbol, :string
has_one :from_currency, ExchangeRate, foreign_key: :from_currency_id
has_one :to_currency, ExchangeRate, foreign_key: :to_currency_id
timestamps()
end
@doc false
def changeset(currency, attrs) do
currency
|> cast(attrs, [:name, :symbol])
|> validate_required([:name, :symbol])
end
This is my exchange_rates table changeset module:
schema "exchange_rates" do
field :rate, :decimal
belongs_to :from_currency, Currency
belongs_to :to_currency, Currency
timestamps()
end
@doc false
def changeset(exchange_rate, attrs) do
exchange_rate
|> cast(attrs, [:rate])
|> validate_required([:rate])
end
Why am I getting this errors:
The Currencies context.
invalid association
from_currency
in schema Currency: associated schema ExchangeRate does not have fieldfrom_currency_id
Elixir
invalid association
to_currency
in schema Currency: associated schema ExchangeRate does not have fieldto_currency_id
Also I’m seeing the following error when running the tests:
test/remittance_service/exchange_rates_test.exs:13
** (Postgrex.Error) ERROR 42703 (undefined_column) column e0.from_currency_id does not exist
query: SELECT e0."id", e0."rate", e0."from_currency_id", e0."to_currency_id", e0."inserted_at", e0."updated_at" FROM "exchange_rates" AS e0
hint: Perhaps you meant to reference the column "e0.from_currency".