2015-11-25 20 views
5

我正在使用Phoenix Framework構建應用程序,並且我已經完成了所有CRUD操作,但是更新/編輯了一個。我已經閱讀並完成了Phoenix編程的書,但我仍然無法執行更新操作。我認爲問題是我需要以某種方式重寫POST方法。Phoenix Framework - 如何更新數據庫中的記錄並使用PATCH方法?

這是我更新的變更:

 def changeset_update(model, params \\ :empty) do 
     model 
     |> cast(params, [], []) 
     |> validate_length(:username, min: 1, max: 20) 
     end 

我的控制器動作:

def update(conn, %{"user" => user_params, "id" => id}) do 
    user  = Repo.get!(User, id) 
    changeset = User.changeset_update(%User{}, user_params) 
    IO.puts changeset.valid? 

    case Repo.update(changeset) do 
     {:ok, user} -> 
      conn 
      |> put_flash(:info, "#{user.name} updated successfully!") 
      |> redirect(to: user_path(conn, :show, id: id)) 
     {:error, changeset} -> 
      render conn, "edit.html", changeset: changeset, user: user 
    end 
    end 

和我的網頁:

<h1>Edit User</h1> 
 

 
<%= form_for @changeset, admin_path(@conn, :update, @user), fn f -> %> 
 
\t <%= if @changeset.action do %> 
 
    <div class="alert alert-danger"> 
 
     <p>Oops, something went wrong! Please check the errors below:</p> 
 
     <ul> 
 
     <%= for {attr, message} <- f.errors do %> 
 
      <li><%= humanize(attr) %> <%= message %></li> 
 
     <% end %> 
 
     </ul> 
 
    </div> 
 
    <% end %> 
 

 
\t <div class="form-group"> 
 
\t \t <input type="hidden" name="_method" value="patch"> 
 
\t \t \t <%= text_input f, :name, placeholder: @user.name, 
 
\t \t \t \t class: "form-control" %> 
 

 
\t \t \t <%= text_input f, :username, placeholder: @user.username, 
 
\t \t \t \t class: "form-control" %> 
 

 
\t \t \t <%= email_input f, :email, placeholder: @user.email, 
 
\t \t \t \t class: "form-control" %> 
 

 
\t \t \t <%= text_input f, :client, placeholder: @user.client, 
 
\t \t \t \t class: "form-control" %> 
 

 
\t \t \t <%= number_input f, :role, placeholder: @user.role, 
 
\t \t \t \t class: "form-control" %> 
 

 
\t \t \t <button type="submit" class="btn btn-primary">Save</button> 
 
\t </div> 
 
<% end %> \t 
 

 
<%= link "Update", to: admin_path(@conn, :update, @user.id), 
 
\t method: :update, data: [confirm: "Update this user's record?"], 
 
\t \t \t class: "btn btn-default btn-xs" %>

(其實我有兩個按鈕,因爲我試圖左右逢源)

隨着第一個按鈕,我得到:

Protocol.UndefinedError at PATCH /admin/users/13 

    protocol Phoenix.Param not implemented for [id: "13"] 

但我有路線/管理/用戶/:ID爲:更新在我routes.ex

行動的第二個按鈕,我得到:

Phoenix.Router.NoRouteError at POST /admin/users/13 

    no route found for POST /admin/users/13 (MyApp.Router) 

這是正常的我猜的,因爲我沒有爲POST這條路線。

任何人都可以幫我解決這個問題嗎?

回答

2

您的PATCH版本實際上工作並且被路由到更新操作。 問題是在該行

|> redirect(to: user_path(conn, :show, id: id)) 

改變,要

|> redirect(to: user_path(conn, :show, id) 

,你應該是不錯的:-)

+0

它沒有工作,也許我應該重讀對重定向的文檔。現在它不更新記錄,但這是另一個問題,我猜想 –

+0

t不會更新記錄,因爲您在changeset_update函數中傳遞了空的必需和可選字段列表來投射函數。 – Jacek

+0

是的,我剛解決了這個問題10分鐘。我的編輯行爲(我傳遞了一張空白地圖)和我的編輯行爲是錯誤的。現在一切正常。 謝謝你們都 –

相關問題