【问题标题】:undefined method `friend' for nil:NilClass Rails Pry issuenil:NilClass Rails Pry问题的未定义方法“朋友”
【发布时间】:2016-01-08 14:45:24
【问题描述】:

我正在使用 ruby​​ on rails 建立朋友之间的关系。我遇到了一些奇怪的事情,pry 工作但服务器没有。不知道如何处理这个。

我得到了一个未定义的方法friend' for nil:NilClass, 引用<% if user.username != friendship.friend.username %> 但是,

    <% @users.zip(@friendships).each do |user, friendship| %>
      <% if user != current_user %>

        <% binding.pry %>
        <% if user.username != friendship.friend.username %>

我在上面撬了一下,看看发生了什么并得到了

     [1] pry(#<#<Class:0x007fbc2dda3040>>)> friendship.friend.username
     User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
     => "Remington_langosh25129"
     [2] pry(#<#<Class:0x007fbc2dda3040>>)> user.username
     => “Remington_langosh25129” 

任何人都知道为什么它在 pry 中有效但在 rails 中无效?

【问题讨论】:

    标签: ruby-on-rails ruby zip iteration each


    【解决方案1】:

    经过一番处理,数组用户和好友的长度不同,所以必须解决如下,

    在模型中,将当前用户的好友 ID 添加到当前用户 ID 的范围内,将解决该问题。

    型号:scope :nonfriends, -&gt; (user) { where.not(id: user.friends.ids &lt;&lt; user.id) }

    控制器:@users = User.nonfriends(current_user)

    查看:&lt;% @users.each do |user| %&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-16
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 2015-11-24
      • 1970-01-01
      • 2014-11-23
      • 2012-09-25
      相关资源
      最近更新 更多