unless current_user.owns_photo? @photo
redirect_to photos_path
end
我有这样的代码,当我运行应用程序时,如果当前的照片不是所有者拥有的,它会将用户重定向到照片的路径。但是,当我运行相同的代码集但将返回添加到它时:
unless current_user.owns_photo? @photo
redirect_to photos_path && return
end
它会导致不规则的结果。经过身份验证的用户可以继续看到不属于它们的东西。但是,当我放弃返回时,它工作得很好。为什么它不能和回报一起工作?我听说在使用redirect_to时返回是一种很好的做法,这样以后就不再执行任何代码了。
def owns_photo?(photo)
photos.include? photo
end
这是工作正常的owns_photo的方法。我只是好奇这个回归的问题。
发布于 2015-11-05 17:20:25
试试redirect_to photos_path and return
。使用and
而不是&&
。这些经营者有不同的优先次序。
键入redirect_to photos_path && return
表示redirect_to (photos_path && return)
,而redirect_to photos_path and return
表示(redirect_to photos_path) and return
发布于 2015-11-05 19:29:35
这与Ruby算子优先有关
&&
(逻辑组合)运算符比and
(逻辑组合)运算符具有更高的优先级。
因此,当您编写这个:redirect_to photos_path && return
时,它被解释为:redirect_to (photos_path && return)
,这不是您想要的。
要解决这个问题,您可以做两件事,或者(在使用&&
运算符时使用括号):
(redirect_to photos_path) && return
或者,使用Rails中通常使用的and
操作符(参见这个职位):
redirect_to photos_path and return
这两种方法都应该像预期的那样起作用,并解决你的问题。
https://stackoverflow.com/questions/33557869
复制