Reputation: 1376
So, naturally, whenever one specifies a resource inside of the routes.rb file like...
resources :users
... this resource generates 7 sample actions...
users#new (GET)
users#create (POST)
users#show (GET)
users#edit (GET)
users#update (PATCH/PUT)
users#destroy (DELETE)
Now, what I want to achieve and cannot do is to add an additional update action to my controller file so that it would be able to update different params. Different to the first update action that is.
Inside of 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 that I have is, in order to make the code above work I need to add a custom update action route to my routes.rb file.
I have tried adding this to my routes...
patch 'users#update_number_two'
put 'users#update_number_two'
... and some other things, but none worked.
If someone could tell me what I should add to my routes.rb file or just nudge me in the right direction, your help is appreciated.
Upvotes: 3
Views: 3676
Reputation: 1963
In order to add another action to a specific resource you need to use 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
then, when you want to update choose different action
of the 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 the results
more information: Adding More RESTful Actions
Upvotes: 7