【问题标题】:How can I define my association correctly?如何正确定义我的关联?
【发布时间】:2012-12-24 16:52:50
【问题描述】:

为什么这段代码会返回错误?
是不是因为我来自CommunityCommunityTopics 的关联设置不正确?

nil:NilClass 的未定义方法 `user_profile'

  <% @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. 社区主题

    • 用户可以根据需要创建社区。​​li>
    • 用户可以根据需要向任何社区发布主题。

这种情况下的关联应该是怎样的?
我的陈述好吗??

用户

has_one :user_profile
has_many :communities
has_many :community_topics

用户资料

belongs_to :user

社区

belongs_to :user
has_many :community_topics

社区主题

belongs_to :user
belongs_to :community

【问题讨论】:

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


    【解决方案1】:

    您的联想似乎没有问题,topic.user 至少在其中一个主题上为零。如果CommunityTopic 应该始终具有user,则您需要实现验证(和NOT NULL 数据库约束)以确保该类上存在用户关联并清理任何现有数据。否则,您将需要进行防御性编码,例如:

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

    【讨论】:

    • 谢谢!!!你说的对!!我有一些没有 user_id 的记录:( 我觉得很愚蠢:( 无论如何谢谢!
    猜你喜欢
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多