2

我还是 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") %>

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

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

4

4 回答 4

3

尝试: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
于 2013-01-24T13:45:38.207 回答
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
于 2013-01-24T14:09:20.940 回答
2

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

于 2013-01-24T13:46:21.703 回答
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
于 2013-01-24T13:45:53.120 回答