How to create two update actions in one controller

So, every time everyone points to a resource inside the routes.rb file like ...

resources :users

... this resource generates 7 selective actions ...

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

      

Problem:

Now what I want to achieve and cannot do is add an additional update act to the controller file so that it can update various parameters . Unlike the first update action.

Inside my users_controller.rb file I have ...

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

      

So the problem I have is, to make the above code work, I need to add a custom update action route to my routes.rb file.

I tried to add this to my routes ...

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

      

... and some other stuff, but none worked.

If someone can tell me what should I add to my route.rb file or just nudge me in the right direction, your help would be appreciated.

+3


source to share


1 answer


To add another action to a specific resource, you need to use member

:

2.10 Adding Additional RESTful Actions

You are not limited to the seven routes that RESTful routing creates by default. If you like, you can 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

      

then when you want to update, select another action

form ( 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

      

run rake:routes

to see results

More information: Adding additional RESTful actions

+6


source







All Articles