【问题标题】:Current controller path without specifying a action in rails当前控制器路径,未在 rails 中指定操作
【发布时间】:2012-12-11 19:58:43
【问题描述】:

我有一个 Rails 应用程序,它有 2 个菜单,其中的菜单会根据用户当前访问的页面而变化。有没有办法告诉 Rails,如果用户正在访问这个控制器,无论访问者是否在 index、edit、create、update、delete 方法上?

我目前正在使用这样的助手,它确实有点乱。

def which_page
  current_page?(root_path) || 
  current_page?(skate_movies_path) ||
  current_page?(new_skate_photos_path(@user)) || 
  current_page?(skate_photos_path) || 
  current_page?(skate_tricks_path)
end

在我看来部分

 <% if which_page %>    
   <%= default_menu %> #upload, #photos, #trick-tips, #goals
 <% else %>
   <%= skate_menu %> #dashboard, #shared-videos, #profile
 <% end %>

问题是这可行,但在整个应用程序中,我总是找到一两个页面,它给我一个路由错误。有什么方法可以在不指定任何操作的情况下告诉用户正在使用哪个控制器和操作?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您可以在ApplicationController 中定义一个before_filter 并将其命名为set_menu

    class ApplicationController < ActionController::Base
      before_filter :set_menu
    
      protected
    
      def set_menu
        @menu = 'default'
      end
    
    end
    

    然后在您希望为您显示不同菜单的每个控制器中,将覆盖set_menu,例如:

    class SkateMoviesController < ApplicationController
    
       protected
    
       def set_menu
         @menu = 'skate'
       end
    
    end
    

    您可以使用set_menu 中的辅助方法action_name 来访问控制器中的当前操作。

    那么在你看来:

    <% if @menu == 'default' %>
      <%= default_menu %>
    <% else %>
      <%= skate_menu %>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 2011-11-25
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多