D.R
D.R

Reputation: 859

Updating changeset through channel. It does not update..

I have table of Subcategory and Category. Subcategory belongs to Category and Category has many subcategory.

In Category table, there are name and subcategory, which is boolean.

What I want to make is that when a user creates a subcategory, it checks whether there are unassigned food (which means a food is not assigned to any subcategories) and if there are not any unassigned food, it updates subcategory value of Category table to true.

def handle_in("create:subcategory", %{"name" => name, "category_id" => category_id}, socket) do 

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

unassignedfood = from(f in Myapp.Food, where: f.category_id == ^category_id and is_nil(f.subcategory_id), select: map(f, [:id, :name])) |> Repo.all 

 if unassignedfood == nil do
  category = Repo.get!(Myapp.Category, category_id)
 |> Myapp.Category.changeset(%{subcategory: true})
 |> Repo.update!
else
 category = Repo.get!(Myapp.Category, category_id)
 |> Myapp.Category.changeset(%{subcategory: false})
 |> Repo.update 
end

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

 broadcast! socket, "subcategories:updated", response

 {:noreply, socket}
end

So I made code like above, if there are not unassigned food, change subcategory value of Category table to true.

I checked that there are not unassignedfood but it does not update.

Is this right way to do?? How can I fix this?

Thanks in advance..

Upvotes: 0

Views: 50

Answers (1)

Dogbert
Dogbert

Reputation: 222148

Repo.all returns a list of records, and an empty result would be [], not nil, so if you want to check for an empty response, you need to change:

if unassignedfood == nil do

to

if unassignedfood == [] do

If you only want to check if a record exists, a more efficient way would be to use Repo.one with limit: 1 and select: true and then check if it returns true:

unassignedfood = from(f in Myapp.Food, where: f.category_id == ^category_id and is_nil(f.subcategory_id), limit: 1, select: true) |> Repo.one

if unassignedfood do
  ...
else
  ...
end

Upvotes: 2

Related Questions