【问题标题】:How to correctly redirect_to @profile in a single line?如何在一行中正确地重定向_到@profile?
【发布时间】:2013-10-22 08:05:11
【问题描述】:
在我的控制器中进行许多检查,如下所示:
if @profile.expired
redirect_to profile_path(@profile.id)
return
end
是否可以将其重构为一行?
Also if using this code it redirects to /profiles.28
其中 28 是 id
如何正确重定向到
/profiles/show/28 or profiles/28 ?
【问题讨论】:
标签:
ruby-on-rails
redirect
methods
routes
refactoring
【解决方案1】:
这很可能是您需要的:
redirect_to(profile_path(@profile.id)) if @profile.expired
您几乎从不(几乎从不,我的意思是实际上从不)在控制器代码中需要 return 语句。如果你真的因为某种原因需要这个,你可以这样做
redirect_to(profile_path(@profile.id)) && return if @profile.expired
至于您的其他问题,我猜您在路线中指定了错误的内容,如果您发布它们,我很乐意更正它们。
【解决方案2】:
我并不完全清楚您想要实现什么,但根据我的最佳猜测,您可以在一行中完成,如下所示:
(@profile.expired) ? (redirect_to profile_path(@profile.id) and return) : 'do something else'