Reputation: 95
I am using devise for user management so it let's user sign up with default email and password fields.
I added new fields/columns into the user model say username, designation and company.
So I have a profile view say with route '/users/1' and a link_to helper which would allow me to edit and update my user info.
By default i can only use users/edit route to edit my user info. How can i manage a new or separate edit and update option with different route say '/users/1/edit' from my profile view.
I read some posts before this but didn't help me. If anyone could outline things i should do. Thanks for reading :))
Edit:
routes file
root 'public#index'
devise_for :users
resources :users do
put 'users/:id/edit', to: 'users#edit'
end
user controller
class UsersController < ApplicationController
before_action :authenticate_user!
after_action :verify_authorized
before_action :set_user, only: %i[ show edit update ]
def index
@users = User.all
authorize User
end
def show
authorize @user
end
def edit
if current_user == @user
@user.update()
end
end
def update
authorize @user
if @user.update(secure_params)
redirect_to users_path, :notice => "User updated."
else
render 'edit'
end
end
private
def secure_params
params.require(:user).permit(:designation, :company,
:username)
end
def set_user
@user = User.find(params[:id])
end
end
In my view to go to edit:
<% if current_user.id == @user.id %>
<%= link_to 'Edit My profile', edit_user_path(@user), method: :edit,
class:"btn btn-primary" %>
<% end %>
Upvotes: 0
Views: 898
Reputation: 1491
If you really want to have a route user/:id/edit
and not use the Devise default users/edit
route(which edits the currently logged-in user). You can do the following:
Let's assume you have a users controller(if you don't have one, create one) and add an edit
action to it which will handle the editing logic:
class UsersController < ApplicationController
# other code
def edit
user = User.find_by(id: params[:id]) # this id will be passed through the route
# Now here you need some authorization logic to prevent users from updating others.
# If you use CanCanCan, Pundit or any other authorization gem then write
# this logic there
if current_user == user
user.update() # do your update logic here with params you have
# render some json or whatever you want
else
# render some error messages in format you are using
end
end
end
This is the controller logic, now in your routes.rb
file you need to register this route:
put 'user/:id/edit', to: 'users#edit'
This will edit the user with ID specified at :id
.
Note again: This is not the approach I would take, I would rather just use the users/edit
route and update the currently logged in user, but you wanted an example of this so do as you will
Upvotes: 1