1
votes

Why does this code return an error?
Is it because my association from Community or CommunityTopics are not set up correctly?

undefined method `user_profile' for nil:NilClass

  <% @community.community_topics.each do |topic| %>
    <li>
    <%= link_to topic.user.user_profile.nickname, community_topic_path(@community, topic) %>
    </li>
  <% end %>

I have 4 models such as

  1. User
  2. UserProfile (This is always set with User one to one)
  3. Community
  4. CommunityTopic

    • Users can create Community as much as they want.
    • Users can post Topics to any Community as much as they want.

In this case how the association should be like?
Is my statement fine??

User

has_one :user_profile
has_many :communities
has_many :community_topics

UserProfile

belongs_to :user

Community

belongs_to :user
has_many :community_topics

CommunityTopics

belongs_to :user
belongs_to :community
1

1 Answers

2
votes

It doesn't look like a problem with your associations, topic.user is nil for at least one of the topics. If CommunityTopic should always have a user you'll need to implement a validation (and NOT NULL database constraint) to ensure the presence of the user association on that class and clean up any existing data. Otherwise you will need to code defensively, e.g.:

<%= link_to topic.user.user_profile.nickname, community_topic_path(@community, topic) if topic.user %>