nil的未定义方法`name':NilClass。找不到@ followed.name但设置了@followed

时间:2014-11-24 08:25:57

标签: ruby-on-rails variables methods undefined

我试图向用户显示另一个用户的信息。 (用户是'朋友')

我得到了:

NoMethodError in Users#show_follow
undefined method `name' for nil:NilClass

因为这段代码:     <%= @ followed.name%>

我无法解释为什么代码无法找到 @followed ,因为它已在控制器中分配,就像我在整个应用中所做的那样。 @active_relationship 似乎正在被分配。 binding.pry也不会在这里打开,再次不确定为什么。有什么想法我无法 @ followed.name 来显示被关注用户的名字?

show_follow.html.erb:

<%= @active_relationship %>
<%= @followed.name %>

user_controller:

  def showf
    if params[:active_relationship]
      @active_relationship = current_user.active_relationships.find_by(params[:active_relationship])
      @followed = @active_relationship.followed
    else 
      "No relationship found"
    end
  end

用户/型号:

has_many :active_relationships,   class_name:  "Relationship",
                                    foreign_key: "follower_id",
has_many :following,           -> { where(relationships: { state: "accepted" } ) },   through: :active_relationships,   source: :followed

关系/型号:

belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"

编辑: 实现了@choco的答案代码,并使binding.pry在视图中工作。输出:

PARAMS: =&GT; {&#34; active_relationship&#34; =&gt;&#34; 28&#34;,&#34; action&#34; =&gt;&#34; show_follow&#34;,&#34; controller&#34; = &GT;&#34;用户&#34;}

CURRENT_USER:   用户负载(0.2ms)SELECT&#34;用户&#34;。* FROM&#34;用户&#34;用户&#34;。&#34; id&#34; = 1 LIMIT 1 =&GT; #

@followed: =&GT;零

@active_relationship: =&GT;零

为什么@active_relationship nill是从被证明存在的参数设置的?

1 个答案:

答案 0 :(得分:1)

改变这个:

def showf
    if params[:active_relationship]
      @active_relationship = current_user.active_relationships.find_by(params[:active_relationship])
     @followed = User.find(@active_relationship.followed_id).name 
     @profile = Profile.find_by_user_id(@followed.id) will give u the object of profile table
    else 
      "No relationship found"
    end
end

这将为您提供预期的输出。