簡體   English   中英

確定是否從視圖或控制器中調用方法

[英]Determine if method is called from a view or controller

在我的應用程序控制器中,我有一種方法可以檢查當前用戶是否有權執行該操作。 我在其他控制器和視圖中都使用此方法。 如何確定是從視圖還是從控制器調用該方法?

這是必需的,因為響應是不同的(從控制器顯示警報和重定向,從視圖隱藏鏈接)。 可能我在這里做的是根本錯誤的事情,也許應該以完全不同的方式解決?

應用控制器:

  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 %>

使用單獨的助手。

View上下文不同於Controller上下文。 混合這些上下文會破壞MVC模式。

檢查self的繼承鏈可能有效:

case self
when ActionController then ...
when ActionView then ...
end

或者查詢self.is_a?(ActionController)self.kind_of?(ActionController)

讓我知道結果如何!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM