【问题标题】:undefined method `name' for nil:NilClass. Can't find @followed.name but @followed is setnil:NilClass 的未定义方法“名称”。找不到@followed.name 但已设置@followed
【发布时间】:2015-01-21 21:54:39
【问题描述】:

我正在尝试向一个用户显示另一个用户的信息。 (用户是“朋友”)

我明白了:

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

因为这段代码:

我无法弄清楚为什么代码找不到 @followed,因为它是在控制器中分配的,就像我在整个应用程序中所做的那样。 @active_relationship 似乎已按应有的方式分配。 binding.pry 也不会在这里打开,再次不确定为什么。任何想法为什么我无法让 @followed.name 显示被关注用户的姓名?

show_follow.html.erb:

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

用户控制器:

  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 在视图中工作。输出:

参数: => {"active_relationship"=>"28", "action"=>"show_follow", "controller"=>"users"}

当前用户: 用户负载 (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1 => #

@followed: => 无

@active_relationship: => 无

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

【问题讨论】:

  • "但 @followed 已设置" - 是的,它已设置为 nil :)
  • 这只是意味着@followed 真的是nil。为什么?你应该拦截它。可能是@active_relationship.followed 也是nil
  • 只是一个错字?您的操作称为showf 而不是show... 如果是错字,请检查params[:active_relationship] 是否包含某些内容。如果没有,把方法名改成show
  • @sss333 请添加您的show_follow 方法
  • showf 是 show_follow 抱歉。路线有:get 'showf' => 'users#show_follow'。

标签: ruby-on-rails variables methods undefined


【解决方案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

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

【讨论】:

  • 每个变量在 Rails 控制台中工作,但在控制器中实现时没有转换到视图。不知道该怎么做..
  • 解决了!应该是 def show_follow .. 不是 def showf。虽然路线重定向正确,但我没有正确设置操作。 :s
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
  • 2017-01-09
相关资源
最近更新 更多