borybar

borybar

Issue whilst creating a form based on many to many relation

Hi,

I am trying to create a form in which a user can choose a product from a list, which at the end will subtract calories of a given product from users daily calorie pool.

I am getting this error: key :foods not found in: %Calorie.UsersFoods.UserFood{__meta__: #Ecto.Schema.Metadata<:built, "users_foods">, food: #Ecto.Association.NotLoaded<association :food is not loaded>, food_id: nil, id: nil, inserted_at: nil, updated_at: nil, user: #Ecto.Association.NotLoaded<association :user is not loaded>, user_id: nil}

What am I doing wrong? This is what I have up until now:

user.ex

defmodule Calorie.Accounts.User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    field :name, :string
    field :username, :string
    field :password, :string, virtual: true
    field :password_hash, :string
    many_to_many(
      :foods,
      Calorie.Products.Food,
      join_through: "users_foods",
      on_replace: :delete
    )

    timestamps()
  end

products/food.ex

defmodule Calorie.Products.Food do
  import Ecto.Query
  import Ecto
  use Ecto.Schema
  import Ecto.Changeset

  schema "foods" do
    field :calories, :integer
    field :name, :string
    many_to_many(
      :users,
      Calorie.Accounts.User,
      join_through: "users_foods",
      on_replace: :delete
    )

    timestamps()
  end

users_foods/user_food.ex

defmodule Calorie.UsersFoods.UserFood do
  use Ecto.Schema
  import Ecto.Changeset

  alias Calorie.Accounts.User
  alias Calorie.Products.Food

  schema "users_foods" do
    belongs_to(:user, User)
    belongs_to(:food, Food)

    timestamps()
  end

  @required_fields ~w(user_id food_id)a
  def changeset(users_foods, params \\ %{}) do
    users_foods
    |> cast(params, @required_fields)
    |> validate_required(@required_fields)
    |> foreign_key_constraint(:user_id)
    |> foreign_key_constraint(:food_id)
    |> unique_constraint([:users, :foods],
      name: :user_id_food_id_unique_index,
      message: "dupa123"
    )

  end
end

Users Food migration

defmodule Calorie.Repo.Migrations.CreateUsersFoods do
  use Ecto.Migration


  def change do
    create table(:users_foods) do
      add :user_id, references(:users)
      add :food_id, references(:foods)
      timestamps()
    end


    create(index(:users_foods, [:user_id]))
    create(index(:users_foods, [:food_id]))

    create unique_index(:users_foods, [:user_id, :food_id], name: :user_id_food_id_unique_index)
  end
end


First Post!

mathieuprog

mathieuprog

The error says

:foods not found in: %Calorie.UsersFoods.UserFood

and indeed we see that :foods is a field inside User schema and not UserFood schema.

Where Next?

Popular in Questions Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
dotdotdotPaul
Okay, I’m having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I’m sure I’...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Other popular topics Top

JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement