2012-04-13 97 views
2

我正在嘗試爲更新我的配置文件頁面創建自定義操作。它不能是常規用戶#編輯或用戶#更新操作,因爲只有管理員可以使用該頁面。Rails 3.如何創建一個自定義的PUT動作?

所以這是我在routes.rb中(方的問題:我怎樣才能使鏈接mydomain.com/users/update_profile成爲代替mydomain.com/update_profile

get 'update_profile/:id' => "users#update_profile", :as => 'update_profile' 

_form.html .erb

<%= form_for @user, :url => update_profile_path(@user) do |f| %> 
    <%= render :partial => "form", :locals => {:f => f} %> 
<% end %> 

users_controller.rb

def update_profile 
    @user = User.find(params[:id]) 
    respond_to do |format| 
    if @user.update_attributes(params[:user]) 
     format.html { redirect_to @user, notice: 'User was successfully updated.' } 
    else 
     format.html { render action: "edit" } 
    end 
    end 
end 

當我提交表單,我得到這樣的:路由錯誤沒有路由匹配[PUT]「/ update_profile/1」

我理解的錯誤,因爲根據rake routes輸出的update_profile動作是GET。

所以我需要將它改爲PUT,但我不知道如何。我如何在routes.rb中設置一個自定義的PUT動作?

+0

是不是像更改'get'update_profile /:id''到'put'update_profile /:id''一樣簡單? – 2012-04-13 15:37:08

回答

4

你應該添加爲users資源

resources :users do 
    member do 
    put :update_profile 
    end 
end 

這樣,它仍然是你的用戶的資源的一部分,該路線將自動生成,並通過類似update_profile_user_path(@user)在你的形式訪問的成員

+0

我得到這個錯誤'無法找到沒有ID的用戶'這個URL爲'http:// localhost:3000/users/1/update_profile'。我也嘗試過'放入'update_profile /:id'',它告訴我我錯過了一個動作。 – leonel 2012-04-13 15:29:49

+0

太棒了,謝謝! :d – leonel 2012-04-13 15:37:17

相關問題