I have a table for tables and orders. Relationship between order and table is that Order
is belong to table and table has many orders. So there is table_id
in one of columns of order table. And also table has a column of current_order
to keep current order_id
that table currently has.
I have a table:show
channel, which shows all lists of tables. And when a user clicks a table, it pushes table:busy
and sends table_id
of clicked table.
So, in the table channel, there is handle_in for table:busy
and I want to create order with table_id
which sent from table:show
channel.
def handle_in("table:busy", %{"table_id" => table_id}, socket) do
table = Repo.get(Pos1.Table, table_id)
changeset = table
|> assoc(:orders)
|> Pos1.Order.changeset(:table_id)
case Repo.insert(changeset) do
{:ok, order}->
changesettable = Table.changeset(table, %{current_order: order.id})
table = Repo.update!(changesettable)
{:noreply, socket}
{:error, changeset} ->
{:reply, {:error, %{error: "Error creating order"}}, socket}
end
end
This is the error message:
---[error] GenServer #PID<0.1327.0> terminating
** (UndefinedFunctionError) function Ecto.Query.__changeset__/0 is undefined or private
(ecto) Ecto.Query.__changeset__()
(ecto) Ecto.Changeset.do_cast/4
(pos1) web/channels/table_channel.ex:18: Pos1.TableChannel.handle_in/3
(phoenix) lib/phoenix/channel/server.ex:225: anonymous fn/4 in Phoenix.Channel.Server.handle_info/2
Above error shows that changeset is not defined... How can I define the changeset to insert data into Orders
table?
Thanks in advance..
---EDIT 1
defmodule Pos1.Order do
use Pos1.Web, :model
schema "orders" do
field :number_of_customers, :integer
field :completed, :boolean, default: false
field :confirmed, :boolean, default: false
field :service_charge, :boolean, default: true
field :total, :integer, default: 0
field :discount, :float, default: 0.0
field :current_select, :integer, default: 1
field :payed, :float
field :finalized, :boolean, default: false
field :served, :boolean, default: false
field :current_round, :integer, default: 0
field :rounds, :integer, default: 1
field :created_date, Ecto.DateTime
belongs_to :table, Pos1.Table
belongs_to :payment, Pos1.Payment
has_many :order_items, Pos1.OrderItem
belongs_to :staff, Pos1.Staff
timestamps
end
@required_fields ~w(number_of_customers table_id completed confirmed
total service_charge current_select finalized served
rounds current_round)
@optional_fields ~w(payment_id discount staff_id payed created_date)
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
end
end
This error is caused by @required_fields
of Orders
model.
I did not pass every @required_fields
so it did not create an order.
I moved some @required_fields
to @optional_fields
and it worked.