Question

I have a page that outputs all of the user profiles that exist in the system. It was working before, I haven't changed anything, and now it is not working. It is telling me that I have "an undefined method `profile_name' for nil:NilClass", but I refer to profile_name many times elsewhere in the application. Here is the index view page:

<% @profiles.each do |profile| %>
    <%= link_to profile.user.inspect, profile_path(profile.user.profile_name) %><br><br>
<% end %>

Here is the profile model:

class Profile < ActiveRecord::Base
    belongs_to :user
end

Here is the user model:

class User < ActiveRecord::Base
    has_one :profile

Here is the profiles controller:

def index
    @profiles = Profile.all
end

Also, the profile table in the database has a column user_id. Plus, I checked my database and all user's have a profile name. On the profile page, I reference @user.profile.(profile attribute) so I know the has_one/belongs_to relationship is working. I can't figure out what to do. Please help.

Thanks.

Was it helpful?

Solution

Do all your Profiles have a user_id value? You might want to consider doing the following to verify that user_id is present for all Profiles:

Profile.pluck :user_id

I suspect a profile object/record does not have a user_id and hence traversing via profile.user.profile_name renders the nil class error.

OTHER TIPS

For whatever reason, your profile.user is nil. Since nil does not have the method .profile_name defined, you get your error.

My guess is there's a profile in @profiles that does not have user_id defined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top