创建凤凰表格并提交时出错

时间:2019-02-07 19:21:56

标签: database elixir phoenix-framework

我是凤凰和不老药的新手。 尝试创建表单以将1个句子提交到数据库中,并且单击提交表单时出现错误。 顺便说一句。我正在学习一些课程,我很困惑。 有代码   Opa_Controller.ex

 defmodule Test.OpaController do
   use Test.Web, :controller
     alias Test.Opa

    def new(conn,_params) do
     struct = %Test.Opa{}
     params = %{}
     changeset = Test.Opa.changeset(struct,params)
     render conn, "sex.html", changeset: changeset
   end
   def create(conn,%{"naziv" => naziv}) do

     changeset = Opa.changeset(%Opa{}, naziv)
    case Repo.insert(changeset) do
      {:ok, post} -> IO.inspect(post)
       {:error, changeset} -> IO.inspect(changeset)
   end
   end
 end

Test.ex

 defmodule Test.Opa do
   use Test.Web, :model

   schema "opala" do
     field :naziv, :string
   end

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

HTML文件

 <%= form_for @changeset, opa_path(@conn, :create), fn f -> %>
     <%= text_input f, :naziv, placeholder: "naziv" %>
     <%= submit "Save Topic" %>
 <% end %>

Router.ex

     get "/", PageController, :index
     get "/opa/new", OpaController, :new
     get "/hello", HelloController, :index
     post "/opa", OpaController, :create

我在航站楼里得到

     [debug] ** (Phoenix.ActionClauseError) could not find a matching      Test.OpaController.create clause
     to process request. This typically happens when there is a
     parameter mismatch but may also happen when any of the other
     action arguments do not match. The request parameters are:

       %{"_csrf_token" => "BDgWfgElRhRdSgoFBTo0BF4+P1YXNgAAtANQOf4Fi+GIlpej+Mt1eg==", "_utf8" => "✓", "opa" => %{"naziv" => "sa"}}

在浏览器中:https://pastebin.com/A2Z3466D

1 个答案:

答案 0 :(得分:0)

create动作需要一个顶级映射键"naziv",可以通过函数定义看到:

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

发送到控制器操作的参数-如错误消息中所示-为:

%{
  "_csrf_token" => "BDgWfgElRhRdSgoFBTo0BF4+P1YXNgAAtANQOf4Fi+GIlpej+Mt1eg==",
  "_utf8" => "✓",
  "opa" => %{"naziv" => "sa"}
}

我们看到,"naziv"嵌套在顶级"opa"键下。

我们实际上想要克服的是更改create函数中的模式匹配,以便它需要顶级"opa"键:

    def create(conn,%{"opa" => opa_params}) do
      changeset = Opa.changeset(%Opa{}, opa_params)
      case Repo.insert(changeset) do
        {:ok, post} -> IO.inspect(post)
        {:error, changeset} -> IO.inspect(changeset)
      end
    end