如何正确定义我的关联?

时间:2012-12-24 16:52:51

标签: ruby-on-rails ruby-on-rails-3 associations

为什么此代码会返回错误?
是因为我CommunityCommunityTopics的关联设置不正确吗?

  

未定义的方法`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个模型,例如

  1. 用户
  2. UserProfile(始终与用户一对一设置)
  3. 社区
  4. CommunityTopic

    • 用户可以根据需要创建社区。
    • 用户可以根据需要将主题发布到任何社区。
  5. 在这种情况下,协会应该如何? 我的陈述好吗??

    用户

    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
    

1 个答案:

答案 0 :(得分:2)

对于您的关联,它看起来不是问题,topic.user对于至少一个主题是{零}。如果CommunityTopic应始终具有user,则需要实现验证(和NOT NULL数据库约束)以确保该类上存在用户关联并清除任何现有数据。否则你需要进行防御性编码,例如:

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