The Manthis
The Manthis

Reputation: 97

in `insert` does not match type :integer

value "2" for Takso.Sales.Booking.estimated_distance in insert does not match type :integer

Hello

I insert nr 2 into text field & press the submit button.

Im trying to create a text input field & add integer value of 2 to the database. Why is this error happening? I dont understand, no documentation or examples how to create a text field that accepts numbers, please help. Trying to find info past 4 hours & nothing :(

new.html.eex

  <div class="form-group">
    <%= text_input booking, :estimated_distance, id: "estimated_distance", class: "form-control" %>
  </div>

booking.ex

  schema "bookings" do
    field :estimated_distance, :integer
    timestamps()
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:estimated_distance])
    |> validate_required([:estimated_distance])
  end

booking_controller.ex

  def new(conn, _params) do
    changeset = Booking.changeset(%Booking{}, %{})
    render conn, "new.html", changeset: changeset
  end


def create(conn, %{"booking" => booking_params}) do
   changeset = Booking.changeset(booking_struct, %{})
   booking = Repo.insert!(changeset)
end

Upvotes: 1

Views: 648

Answers (2)

The Manthis
The Manthis

Reputation: 97

<%= number_input booking, :distance, id: "distance", class: "form-control" %>

you can change it to number input, but real issue was this, I still dont understand why tho, but the problem got solved:

Inside booking_controller.ex

Before:

  def create(conn, %{"booking" => booking_params}) do

    booking_struct = Ecto.build_assoc(user, :bookings, Enum.map(booking_params, fn({key, value}) -> {String.to_atom(key), value} end))   
    changeset = Booking.changeset(booking_struct, %{})
                |> Changeset.put_change(:status, "open")

    booking = Repo.insert!(changeset)

AFTER:

  def create(conn, %{"booking" => booking_params}) do

    booking_struct = Ecto.build_assoc(user, :bookings, Enum.map(booking_params, fn({key, value}) -> {String.to_atom(key), value} end))
    {d, _} = Integer.parse(booking_params["distance"])   
    changeset = Booking.changeset(booking_struct, %{})
                |> Changeset.put_change(:status, "open")
                |> Changeset.put_change(:distance, d)

    booking = Repo.insert!(changeset)

Upvotes: 1

Minh-Khang
Minh-Khang

Reputation: 444

estimated_distance is integer

  schema "bookings" do
    field :estimated_distance, :integer
    timestamps()
  end

But the params from input returns string type. Therefor it says "2" not match integer.

So I suggest parsing the param to integer by using Integer.parse/2 or changing field :estimated_distance, :string for easy

Upvotes: 0

Related Questions