2012-01-13 43 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"