lflores
lflores

Reputation: 3800

Rails routing confusion due to :id

I am using devise for authentication. When signing up users create a profile name that I would like to use as their profile route. So, it might look like this: www.myapp.com/profile-name. The problem I'm running into is with the routes not going to the right place.

routes.rb

resources :majors do 
  resources :reviews
end 

devise_for :users

...

match '/:id' => 'users#show', as: :user_profile

I've placed the :user_profile route at the bottom of my routes file. Part of my rake routes looks like this:

major GET            /majors/:id(.:format)   majors#show
user_profile GET     /:id(.:format)          users#show

On the profile page (myapp.com/my-custom-profile-name) there are no problems. But on the majors show page I use the user_profile_path to link to a user's profile and the url is www.myapp.com/:id - with the :id being the major :id. So, the :id of the major is getting mixed in with the user_profile :id.

My users controller looks like this:

def show
  @user = User.find_by_profile_name(params[:id])
  @reviews = @user.reviews
end  

I have changed the url around, tested it on different areas, changed the order of my routes file, searched and tested this all day long. I cannot figure out what I'm missing. I think it's really simple but it's eluding me. Any ideas?


SOLUTION:

The solution was first get the routes correct. Since I've created a custom, dynamic url (myapp.com/user-profile-name) I needed to call the id in the route:

get '/:id' => 'users#show', as: :id  

That changed my routes to look like this:

id GET        /:id(.:format)              users#show

Users share reviews and their name is posted next to their review. I was having trouble linking to their profile from their name on their review. I was able to do that on the view like this:

<%= link_to review.user.profile_name, id_path(review.user.profile_name) %>

Upvotes: 1

Views: 358

Answers (1)

Nick Messick
Nick Messick

Reputation: 3212

To get to a specific user profile, you need to pass the user profile ID into the user_profile named route:

user_profile_path(@user)

Upvotes: 1

Related Questions