【发布时间】: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