Haseeb Ahmad
Haseeb Ahmad

Reputation: 8730

Routing issue in ruby on rails

For user profile I make an action in home controller and I want that when user click on my profile link only shows www.abc.com/profile

For it I do

get '/profile' => 'home#profile'

But now issue is that there is a need to send user id along with that.If I send it in format then url become

www.abc.com/profile.4

I want that url remains '/profile' and Id of user also send

Upvotes: 1

Views: 50

Answers (3)

Richard Peck
Richard Peck

Reputation: 76774

This is because you're setting it as a member route (it expects to pass the id for the controller). You need to replace it with a collection route, if you're going to nest it:

#config/routes.rb
devise_for :users ... do
   get :profile, to: "home#profile", on: :collection, as: :profile #-> url.com/users/profile
end

You'd then be able to access the profile as follows:

<%= link_to "Profile", users_profiles_path, if user_signed_in? %>

If you wanted to make it so that you could access profile without nesting, your route would work:

#config/routes.rb
get "profile", to: "home#profile", as: :profile

<%= link_to "Profile", profile_path if user_signed_in? %>

Controller

We have a setup similar to this, let me explain the controller setup...

#app/controllers/users_controller.rb
class UsersController < ApplicationController 
   before_action :authenticate_user!

   def edit
      @user = current_user
   end
   def update
      @user = current_user
      ...
   end
end

This gives us the ability to use the following (we also use devise):

#config/routes.rb
resource  :profile, path: "profile", controller: :users, path_names: { edit: "" }, only: [:edit, :update]   #-> domain.com/profile

Upvotes: 2

Hemanth M C
Hemanth M C

Reputation: 436

in devise gem they had mentioned current_user model so use

current_user.id 

to find the User id so that in your profile action do like this, and pass the user id of current user so that you can easily fetch his details

Upvotes: 0

mb_s88
mb_s88

Reputation: 392

If you want the url to stay /profile then you'll have to rely on your login implementation. I've not used devise myself, but according to the documentation it provides you with a current_user method to use in your controllers. So your HomeController#profile would look something like this:

def profile
  @user = current_user
  render :profile
end

That way you don't need the client to send the id to you, because (as I understand it) this should be the profile page of the logged in user, which you should already have information about through devise.

Otherwise you need to allow the id to come through the path by defining the route like so:

get '/profile/:id' => "home#profile"

Upvotes: 1

Related Questions