【问题标题】:How to get the name of the current controller into my helper function?如何将当前控制器的名称放入我的辅助函数中?
【发布时间】:2013-01-24 13:36:09
【问题描述】:

我还是 Rails 新手,我有以下 section_links 作为我的 Rails 应用程序的主导航:

<%= section_link(Organisation.model_name.human(:count => 2), 'organisations', organisations_path) %>
<%= section_link(Person.model_name.human(:count => 2), 'people', people_path) %>
<%= section_link(Project.model_name.human(:count => 2), 'projects', projects_path) %>           
<%= section_link(Invoice.model_name.human(:count => 2), 'invoices', invoices_path) %>       
<%= section_link(Payment.model_name.human(:count => 2), 'payments', payments_path) %>

我还写了这个非常基本的辅助函数:

def section_link(title, section, path)
  options = {}  
  options[:class] = 'current' if section == controller_name
  link_to title, path, options
end

有什么办法可以干掉这个辅助函数,所以我可以这样说来建立一个链接:

&lt;%= section_link("Organisations") %&gt;

我已经尝试了几个小时,但我不知道如何将当前控制器的名称传递给我的辅助函数。

感谢您对此的任何帮助...

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2


    【解决方案1】:

    可能是这样的

    def section_link(model)
       title = model.singularize.capitalize.constantize.model_name.human(:count => 2)
       section = model.downcase.pluralize
       path = {controller: model.pluralize.downcase, action: :index }
       options = {}  
       options[:class] = 'current' if section == controller_name
       link_to title, path, options
    end
    

    【讨论】:

      【解决方案2】:

      试试:params[:controller] or controller.controller_name

      <%= section_link(params[:controller], Organisation.model_name.human(:count => 2), 'organisations', organisations_path) %>
      
      def section_link(current_controller, title, section, path)
       options = {}  
       options[:class] = 'current' if section == controller_name
       link_to title, path, options
      end
      

      【讨论】:

        【解决方案3】:

        您可以尝试request.params[:controller] 在助手中获取控制器名称。我不确定它是否有效,但我相信你可以从 params 获取控制器名称。

        【讨论】:

          【解决方案4】:
          def current_link_to label, path, options = nil
              options ||= {} 
              options[:class] =  [options[:class], (current_page?(path) ? "active" : nil)].compact.join(" ")
              link_to label, path, options
          end
          

          【讨论】:

          • current_page? => 不知道那个,很好用
          猜你喜欢
          • 2011-09-20
          • 1970-01-01
          • 1970-01-01
          • 2015-11-09
          • 2011-02-05
          • 1970-01-01
          • 1970-01-01
          • 2020-04-13
          • 1970-01-01
          相关资源
          最近更新 更多