Ruby on Rails - 如何将当前控制器的名称获取到我的帮助程序函数中



我仍然是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

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

<%= section_link("Organisations") %>

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

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

也许是这样的

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
您可以

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

尝试:params[:controller] 或 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
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

相关内容

  • 没有找到相关文章

最新更新