Search code examples
elixirphoenix-frameworkecto

Query Repo Using a String


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?


Solution

  • 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.