5

I am using Phoenix with Ecto to query a database for a single record by the primary key. All of the documentation/examples show the usage as in a Phoenix Controller:

def show(conn, %{"id" => id}) do
  m = Repo.get(MyModel, id)

  ...
end

However, all params in Phoenix are strings, so this throws a ** (Ecto.InvalidModel) model App.MyModel failed validation when , field id had type string but type integer was expected. I have been working around this in my controllers by doing something like:

def show(conn, %{"id" => id}) do
   m = String.to_integer(id) |> find_my_model_by_id

  ...
end

defp find_my_model_by_id(id) do
 Repo.get(MyModel, id)
end

The problem is I haven't seen anyone else doing this sort of type conversion. I'm worried I don't have Phoenix or Ecto set up correctly. Is there a Phoenix/Ecto convention I am missing that would automatically coerce my id argument for Repo.get/2 to an int?

Kombo
  • 2,371
  • 3
  • 34
  • 64

2 Answers2

0

Your code is correct. In the upcoming Ecto version we want to add automatic casting for cases like this. But for now, you need to cast it manually.

Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
José Valim
  • 50,409
  • 12
  • 130
  • 115
0

tried on Ecto 2.2.0, it still doesn't automatically cast a string to integer in my query

where: u.user_id == ^user_id,

Got error:

(ArgumentError) Postgrex expected an integer in -9223372036854775808..9223372036854775807, got "33133". Please make sure the value you are passing matches the definition in your table or in your query or convert the value accordingly.
Nhut Dinh Ba
  • 354
  • 1
  • 6