2013-01-24 2 views
2

는 아직도 레일에 새로운 오전 나는 내 레일 응용 프로그램에 대한 기본 탐색 역할을 section_links 다음과 같습니다현재 컨트롤러의 이름을 도우미 함수로 가져 오는 방법은 무엇입니까?

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

인가가 :

<%= 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) %> 

내가이 아주 기본적인 도우미 함수를 썼다을 어떤 방법이 도우미 함수를 건조, 그래서 나는 이런 식으로 뭔가가 링크하기 위해 말할 수있다 :

<%= section_link("Organisations") %>

몇 시간 동안이 작업을 시도했지만 현재 컨트롤러의 이름을 도우미 함수에 전달하는 방법을 모르겠습니다. 이 어떤 도움을

감사합니다 ...

답변

2

어쩌면 뭔가

같은
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 
+0

정말 잘 작동합니다. 감사합니다! – Tintin81

+0

@ Tintin81 그게 당신이 원했던 것이고 효과가 있다면 대답을 대답으로 표시하십시오. – Raed

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 
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 
+0

'CURRENT_PAGE?'=> 모르는 일이 매우 편리 –

2

당신은 도우미에서 컨트롤러 이름을 얻을 request.params[:controller]을 시도 할 수 있습니다. 작동하는지 모르겠지만 컨트롤러 이름을 params에서 얻을 수 있다고 확신합니다.

+0

최고의 대답, 감사합니다! –

관련 문제