为什么此代码会返回错误?
是因为我Community
或CommunityTopics
的关联设置不正确吗?
未定义的方法`user_profile'代表nil:NilClass
<% @community.community_topics.each do |topic| %>
<li>
<%= link_to topic.user.user_profile.nickname, community_topic_path(@community, topic) %>
</li>
<% end %>
我有4个模型,例如
CommunityTopic
在这种情况下,协会应该如何? 我的陈述好吗??
用户
has_one :user_profile
has_many :communities
has_many :community_topics
用户配置
belongs_to :user
社区
belongs_to :user
has_many :community_topics
CommunityTopics
belongs_to :user
belongs_to :community
答案 0 :(得分:2)
对于您的关联,它看起来不是问题,topic.user
对于至少一个主题是{零}。如果CommunityTopic
应始终具有user
,则需要实现验证(和NOT NULL数据库约束)以确保该类上存在用户关联并清除任何现有数据。否则你需要进行防御性编码,例如:
<%= link_to topic.user.user_profile.nickname, community_topic_path(@community, topic) if topic.user %>