我还是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") %>
我已经尝试了几个小时,但我不知道如何将当前控制器的名称传递给我的帮助函数。
感谢您对此提供任何帮助......
答案 0 :(得分:3)
尝试: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
答案 1 :(得分:3)
也许像
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 :(得分:2)
您可以尝试request.params[:controller]
在助手中获取控制器名称。我不确定它是否有效,但我确信你可以从params获得控制器名称。
答案 3 :(得分:1)
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