Katharina Schreiber
Katharina Schreiber

Reputation: 1371

Rails link_to user_profile_path doesn't find user.id

I have a user and profile model, and also two controllers. I can go to a page where all profiles are displayed, but if I want to view one single profile, this won't work. Here is the line in profiles - index.html.erb:

<%= link_to 'Go to profile', user_profile_path(@user, profile) %>

I get an error,

user_id is nil.

I also tried many other variations like :

user_profile_path(user.id, user.profile.id)
user_profile_path(@user, @profile)
user_profile_path(@profile)
user_profile_path(profile)

And I always get different mistakes. I have no ideas anymore. Please help!

Upvotes: 1

Views: 337

Answers (3)

Katharina Schreiber
Katharina Schreiber

Reputation: 1371

Since my routes are a bit complicated, and the profiles#index actually shows all the profiles, but still having the current_user logged in, the right path is

<td><%= link_to 'Show user profile', user_profile_path(current_user, profile) %></td>

This way me as a current user can see other profiles. That was a tought one 🤬

Upvotes: 0

iseitz
iseitz

Reputation: 71

If in your profile model there is a relation belongs_to :user, then you could try to set @user in the show method in your profiles_controller.rb It would look something like:

@user = current_user

Here we are assuming that the user goes to see his/hers own profile. And this would be the best practice to avoid messing with personal data.

If we are talking about visiting random profile from the list, then you have this kind of link located near each profile that is listed on the #index page and it should par default pick the profile.id. In this case:

@profile = Profile.find(params[:id])
@user = User.find(@profile.user_id)#This part will depend on how you relate profile and user.

It can also be @user = User.find(@profile.user.id)

Again as ricks mentioned it is true that the profile structure would be more efficient as a part of User model.

Upvotes: 1

ricks
ricks

Reputation: 3324

You shouldn't make a model for profile if profile is just displaying attributes that belong to a user.

It would make sense if your user has all the attributes that will be displayed in the profile view, such as first_name, last_name, email, ect..

Then you can have a profile controller and create a view for the users profile where you can just get the information from the user object and display it.

If you want to show all the profiles, then you would be showing a view of all the users with their attributes being displayed in another view. There is no need for a second model.

Upvotes: 1

Related Questions