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?

4

2 回答 2

0

你的代码是正确的。在即将推出的 Ecto 版本中,我们希望为此类情况添加自动转换。但是现在,您需要手动投射它。

于 2014-12-18T10:47:47.450 回答
0

在 Ecto 2.2.0 上尝试过,它仍然不会在我的查询中自动将字符串转换为整数

where: u.user_id == ^user_id,

得到错误:

(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.
于 2018-07-02T07:26:19.873 回答