D.R
D.R

Reputation: 859

How can I insert foreign key id through using channel?

I have tables, Category and Subcategory.

Category has many subcategories and Subcategory belongs to category.

In my channel handle_in, there is a function to insert subcategory like below.

def handle_in("create:subcategory", %{"name" => name, "category_id" => category_id}, socket) do 
changeset = Subcategory.changeset(%Subcategory{name: name, category_id: category_id})
|>Repo.insert

subcategories = from(p in Pos8.Subcategory, select: map(p, [:id, :name, :category_id])) |> Repo.all
response = %{subcategories: subcategories}

  broadcast! socket, "subcategories:updated", response

 {:noreply, socket}
end

So basically, what I want to do is to create subcategory with name and category_id passing. But it triggers a error that Myapp.Subcategory.category_id in insert does not match type :id (ecto) lib/ecto/repo/schema.ex:691: Ecto.Repo.Schema.dump_field!/6 (ecto) lib/ecto/repo/schema.ex:700: anonymous fn/6 in Ecto.Repo.Schema.dump_fields!/5

How can I insert category_id when I create subcategory?

Thanks in advance..

Upvotes: 0

Views: 503

Answers (2)

Justin Wood
Justin Wood

Reputation: 10061

If you were to do a test, you would notice that the category_id is a string. This is okay when you are trying to find a value in the database using something like Repo.get/3, but unfortunately it will not be okay when trying to insert the raw value.

However, you should just be able to do something like String.to_integer(category_id) and you will be able to insert it just fine.

So your final insert line would look like

changeset = 
  Subcategory.changeset(%Subcategory{name: name, 
                                     category_id: String.to_integer(category_id)})
  |> Repo.insert()

As @Dogbert points out in the comments, you can just let the changeset function deal with the conversion.

changeset = 
  Subcategory.changeset(%Subcategory{}, %{name: name, category_id: category_id})
  |> Repo.insert()

This has the benefit of working not just on integer types.

Upvotes: 2

ash
ash

Reputation: 711

This might work:

import Ecto.Changeset
parent = Repo.get!(Category, category_id)
subcategory = cast(%Subcategory{}, %{name: name})
              |> put_assoc(:category, parent) 
              |> Repo.insert!

Upvotes: 0

Related Questions