Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails route dependent on current user

I'd like to create a rails route for editing a user's profile.

Instead of having to use /users/:id/edit, I'd like to have a url like /edit_profile

Is it possible to create a dynamic route that turns /edit_profile into /users/{user's id}/edit, or should I do thing in a controller or?

like image 585
Lowgain Avatar asked May 04 '10 00:05

Lowgain


2 Answers

You might want to create a separate controller for this task but you could also continue using users_controller and just check whether there is a params[:id] set:

def edit
  if params[:id]
    @user = User.find(params[:id])
  else
    @user = current_user
  end
end

But you should note that /users normally routes to the index action and not show if you still have the map.resources :users route. But you could set up a differently called singular route for that:

map.resources :users
map.resource :profile, :controller => "users"

This way /users would list all the users, /users/:id would show any user and /profile would show the show the currently logged in users page. To edit you own profile you would call '/profile/edit'.

like image 74
Tomas Markauskas Avatar answered Nov 14 '22 13:11

Tomas Markauskas


Since a route and controller serve two different purposes, you will need both.

For the controller, assuming you're storing the user id in a session, you could just have your edit method do something like:

def edit
  @user = User.find(session[:user_id])
end

Then have a route that looks something like:

map.edit_profile "edit_profile", :controller => "users", :action => "edit"

This route would give you a named route called edit_profile_path

like image 3
Peter Brown Avatar answered Nov 14 '22 14:11

Peter Brown