Phoenix / Elixir / Ecto.CastError:值`" new"`在`where`中无法强制转换为:查询中的id:来自MyApp.User中的u,

时间:2016-03-23 04:54:37

标签: elixir phoenix-framework ecto

我正在使用Programming Phoenix,在我的应用中添加了一个新用户功能:

我收到以下错误:

deps/ecto/lib/ecto/repo/queryable.ex:188: value `"new"` in `where` cannot be cast to type :id in query:

from u in Microflow.User,
where: u.id == ^"new"

Error when casting value to `Microflow.User.id`

deps / ecto / lib / ecto / repo / queryable.ex:188的代码块在这里:

defp query_for_get(_repo, queryable, id) do
  query = Queryable.to_query(queryable)
  model = assert_model!(query)
  primary_key = primary_key_field!(model)
  Ecto.Query.from(x in query, where: field(x, ^primary_key) == ^id) 

第188行:

Ecto.Query.from(x in query, where: field(x, ^primary_key) == ^id) 

用户控制器更新:

def create(conn, %{"user" => user_params}) do
  changeset = User.changeset(%User{}, user_params)
  case Repo.insert(changeset) do
    {:ok, user} ->
      conn
      |> put_flash(:info, "#{user.name} created!")
      |> redirect(to: user_path(conn, :index))
  {:error, changeset} ->
    render(conn, "new.html", changeset: changeset)
  end
end

EEX示例:

<h1>New User</h1>

 <%= form_for @changeset, user_path(@conn, :create), fn f -> %>
    <div class="form-group">

 <%= text_input f, :name, placeholder: "Name", class: "form-control" %>
    </div>

<%= form_for @changeset, user_path(@conn, :create), fn f -> %>
  <div class="form-group">

<%= text_input f, :name, placeholder: "Name", class: "form-control" %>
  </div>

<div class="form-group">
<%= text_input f, :username, placeholder: "Username", class: "form-control" %>
</div>

<div class="form-group">

<%= password_input f, :password, placeholder: "Password", class: "form-control" %>
</div>

<%= submit "Create User", class: "btn btn-primary" %>

<% end %>

任何想法我能做什么?谢谢,如果你能提供帮助。

此处相关讨论:

http://slack.elixirhq.com/phoenix/2015-09-11/

1 个答案:

答案 0 :(得分:0)

通过删除此行修复:

get "/users/:id", Microflow.UserController, :show

并添加此内容:

resources "/users", Microflow.UserController 

我不知道为什么一个小的改变会引起这样的错误,但我已经重新检查了5次。我已经看到很多路由错误,但没有提出这样一个模糊的错误消息。