在我的应用程序控制器中,我有一个方法来检查当前用户是否有权执行该操作。我从其他控制器和视图中使用此方法。如何确定是从视图还是控制器调用该方法?
这是必需的,因为响应不同(从控制器显示警报和重定向,从视图时隐藏链接)。可能我在这里做了一些根本错误的事情,我应该解决它完全不同的问题?
应用程序控制器:
helper_method :is_allowed
# Check if current user is allowed to perform action
def is_allowed(required_level)
# Required level is level and all levels above (1=high, 3=low)
# level 1: user
# level 2: company_admin
# level 3: admin
case required_level
when 'company_admin'
unless current_user.role == 'company_admin' || current_user.role == 'admin'
flash[:alert] = I18n.t(:not_allowed)
redirect_to root_path
end
when 'admin'
unless current_user.role == 'admin'
flash[:alert] = I18n.t(:not_allowed)
redirect_to root_path
end
end
end
从其他控制器调用(这可行):
before_filter :only => [:destroy] do |c| c.is_allowed 'company_admin' end
从视图调用(确实有效,但不应重定向,但只能隐藏链接):
<% if is_allowed('company_admin') %>
<td><%= link_to I18n.t(:delete), relation, :method => :delete, :confirm => I18n.t(:sure) %></td>
<% end %>
答案 0 :(得分:1)
使用单独的助手。
View
上下文与Controller
上下文不同。混合这些上下文打破了MVC模式。
答案 1 :(得分:0)
检查self
的继承链可能有效:
case self
when ActionController then ...
when ActionView then ...
end
或者可以查询self.is_a?(ActionController)
或self.kind_of?(ActionController)
。
让我知道事情的结果!