2012-01-13 25 views
1

是否可以從更新操作/方法以外的操作/方法進行更新?例如在我的用戶控制器中,我已經有了用戶帳戶其他部分的更新方法。如何使用Ruby on Rails中的替代更新方法更新我的方法?

我需要一個單獨的更改我的用戶密碼。是否有可能有這樣的事情:

def another_method_to_update 
    user = User.authenticate(current_user.email, params[:current_password]) 
    if user.update_attributes(params[:user]) 
    login user 
    format.js { render :js => "window.location = '#{settings_account_path}'" } 
    flash[:success] = "Password updated" 
    else 
    format.js { render :form_errors } 

    end 
end 

然後有我的更改密碼錶知道使用該方法執行更新?

它有3個領域:當前密碼新密碼確認新密碼

,我使用Ajax顯示錶單錯誤。

親切的問候

+0

當然,你可以有任意數量的方法來更新/刪除任何你喜歡/編輯。你需要定義他們的路線。 – 2012-01-13 11:16:35

回答

0

是的; update操作只是一個默認設置,使基於REST的界面非常簡單。您需要確保在config/routes.rb中有一個POST路由,其中​​users#another_method_to_update假設您正在UsersController(和Rails 3)中執行所有這些操作,但您的問題的基本答案是模型操作(包括更新字段)可以在可用模型的任何地方完成。

可以調用哪些模型方法和調用哪些控制器方法之間沒有任何聯繫。

0

爲什麼你想要使用另一條路線呢?遵循慣例,使用默認路線。如果我理解正確,您的頁面包含一個密碼更新表單。

我們可以在更新方法寫整個代碼這一點,但是這是更清潔,更不言自明:

def update 
    change_password and return if change_password? 
    # old code of your update method 
    # ... 
end 

private 

def change_password? 
    !params[:current_password].nil? 
end 

def change_password 
    user = User.authenticate(current_user.email, params[:current_password]) 
    respond_to do |format| 
    if user.update_attributes(params[:user]) 
    login user 
    flash[:success] = "Password updated" 
    format.js { render :js => "window.location = '#{settings_account_path}'" } 
    else 
    format.js { render :form_errors } 
    end 
    end 
end 

這是一個更容易理解的人誰都會看你的代碼,因爲你仍然調用更新方法來更新您的模型,然後執行自定義操作。

我也修復了您的自定義方法代碼。

0
在配置/ routes.rb中

puts "users/other_update_method"