Ruby on rails nil:NilClass的未定义方法“name”。找不到@followed.name,但已设置@followed
我试图显示一个用户,另一个用户的信息。用户是“朋友” 我得到:Ruby on rails nil:NilClass的未定义方法“name”。找不到@followed.name,但已设置@followed,ruby-on-rails,variables,methods,undefined,Ruby On Rails,Variables,Methods,Undefined,我试图显示一个用户,另一个用户的信息。用户是“朋友” 我得到: NoMethodError in Users#show_follow undefined method `name' for nil:NilClass 由于这段代码: 我不明白为什么代码找不到@followed,因为它是在控制器中分配的,就像我在整个应用程序中所做的那样@积极的_关系似乎被分配到了应有的位置。binding.pry也不会在这里打开,也不知道为什么。你知道为什么我不能让@followerd.name显示被跟踪用户的
NoMethodError in Users#show_follow
undefined method `name' for nil:NilClass
由于这段代码:
我不明白为什么代码找不到@followed,因为它是在控制器中分配的,就像我在整个应用程序中所做的那样@积极的_关系似乎被分配到了应有的位置。binding.pry也不会在这里打开,也不知道为什么。你知道为什么我不能让@followerd.name显示被跟踪用户的姓名吗
show_follow.html.erb:
用户/型号:
关系/模式:
编辑:
从@choco实现了应答代码,并获得binding.pry以在视图中工作。产出:
参数:
=>{active_relationship=>28,action=>show_follow,controller=>users}
当前用户:
用户加载0.2ms从users.id=1的用户中选择用户。*限制1
=>
@随后:
=>零
@主动关系:
=>零
为什么@active_relationship为nill,而它是从已证明存在的参数设置的???更改此项:
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
这将为您提供预期的输出。但是@followed被设置为-是的,它被设置为nil:这只意味着@followed实际上是nil。为什么?你应该拦截它。可能是@active_relationship.nellis也只是一个typpo吗?您的操作称为showf而不是show。。。如果它是一个typpo,那么检查params[:active_relationship]是否包含某些内容。如果不是,请将方法名称更改为show@sss333请添加您的show\u follow方法showf为show\u follow抱歉。路由有:get'showf'=>'usersshow_follow'。每个变量都在rails控制台中工作,但在控制器中实现时没有转换到视图中。。不知道该怎么办..解决了!本应被证明是正确的。。不是def showf。当路由正确重定向时,我没有正确设置操作:s
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"
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