如何在一个控制器中创建两个更新操作

How to create two Update actions in one Controller

因此,很自然地,每当有人在 routes.rb 文件中指定资源时,例如...

resources :users

...此资源生成 7 个示例操作...

users#new     (GET)
users#create  (POST)
users#show    (GET)
users#edit    (GET)
users#update  (PATCH/PUT)
users#destroy (DELETE)

问题:

现在,我想要实现但不能做的是向我的控制器文件添加一个额外的更新操作,以便它能够更新不同的参数。与第一个更新操作不同。

在我的 users_controller.rb 文件中我有...

class UsersController < ApplicationController
  .
  .
  .
  # First update action
  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated"
      redirect_to @user
    else
      render 'edit'
    end
  end

  # Second update action
  def update_number_two
    @user = User.find(params[:id])
    if @user.update_attributes(user_other_params)
      flash[:success] = "Other params updated"
      redirect_to @user
    else
      render 'other_view' 
    end
  end

  private

    # Params for the first action
    def user_params
      params.require(:user).permit(:name, :email, :password, :password_confirmation)
    end

    # Params for the second action
    def user_other_params
      params.require(:user).permit(:other_param)
    end
end

所以我遇到的问题是,为了使上面的代码正常工作,我需要将自定义更新操作路由添加到我的 routes.rb 文件中。

我试过将它添加到我的路线中...

patch 'users#update_number_two'
put   'users#update_number_two'

...和其他一些东西,但是 none 有效。

如果有人能告诉我应该在我的 routes.rb 文件中添加什么,或者只是将我推向正确的方向,我们将不胜感激。

为了向特定资源添加另一个操作,您需要使用 member:

2.10 Adding More RESTful Actions

You are not limited to the seven routes that RESTful routing creates by default. If you like, you may add additional routes that apply to the collection or individual members of the collection.

resources :users do
  member do
    patch :update_number_two
    put :update_number_two
  end
end

然后,当您要更新时,请选择不同的 action 形式 (update_number_two_user_path || /users/:id/update_number_two)

update_number_two_user PATCH  /users/:id/update_number_two(.:format) users#update_number_two
                       PUT    /users/:id/update_number_two(.:format) users#update_number_two

运行rake:routes查看结果

更多信息:Adding More RESTful Actions