我是Rails的新手,我刚刚写了这篇文章,我需要帮助重构,因为我不认为视图中应该有那么多逻辑?
http://i.imgur.com/06ViCkV.png(代码块没有显示正确,所以我创建了一个截图并上传到imgur。)
谢谢。
编辑:
<% if @match.creator == current_user or @match.opponent == current_user %>
<% if Result.where(user_id: current_user.id, match_id: @match.id).exists? %>
You've submitted your results. thank you.
<% else %>
<%= render('results/form') %>
<% end %>
<% else %>
you don't have access to this.
<% end %>
答案 0 :(得分:0)
是的,我会尝试解决这个预览。考虑进行前回调以验证创建者是否为特定用户 - 如果是,则不执行任何操作,否则将重定向到受限访问页。
before_filter :authorize_creator, only: [:show]
def show
@result = blah blah
end
private
def authorize_creator
redirect_to blah_path unless [@match.creator, @match.opponent].include?(current_user)
end
答案 1 :(得分:0)
相信你的直觉;在视图中肯定不会有那么多逻辑。此外,永远不应该对视图中嵌入的数据库进行显式调用。控制器应该只关心渲染或重定向的内容,也许只是非常简单的初始化。更多涉及的逻辑可以进入帮助器或装饰器。 (默认情况下,装饰器不在轨道中,但Draper gem和其他装置可以很容易地包含它们。)
清理视图的'胖控制器'方式可能类似于:
def show
@match = Match.find(params[:id])
if [@match.creator, @match.opponent].include?(current_user)
@results_submitted = Result.where(user_id: current_user.id, match_id: @match.id).exists?
else
render text: "You don't have access to this", status: 403 and return
end
end
我们的想法是为视图预先计算内容,如果可以,甚至可以从视图中删除条件。您也可能希望使用像Pundit或CanCanCan这样的宝石来帮助控制对匹配的访问。