Question

Im trying to render a dynamic nav menu using a application helpers but all get is a hash

when I load the page this is all that it displays

[#<Project id: 15, title: "downer", created_at: "2012-07-03 08:36:16", updated_at: "2012-07-03 08:36:16", company_id: 2>]

here is the code that is used in the application helper

def project_list(user)
    company ||= user.profile.company
    projects ||= company.projects 
    projects.each do |project|
      link_to project.title, company_project_path(company, project)
      project.scopes.each do |scope|
        link_to scope.name, company_project_scope_path(scope.company, scope.project, scope)
      end
    end
  end

and

_nav.erb.html

<%= project_list(current_user) %>
Was it helpful?

Solution

In ruby a method returns the last evaluated expression by default. Also, each returns the array/hash which was iterated upon. So effectively your project_list is returning projects back to the view. You should change your method to return the html you want to insert:

def project_list(user)
  html = ''
  company ||= user.profile.company
  projects ||= company.projects 
  projects.each do |project|
    html += link_to project.title, company_project_path(company, project)
    project.scopes.each do |scope|
      html+= link_to(scope.name, company_project_scope_path(scope.company, scope.project, scope))
    end
  end
  return html.html_safe
end

OTHER TIPS

Your enumerable #each is returning the last object in the collection which becomes the return value of the project list method.

You need to build up a list of tags then return that object.

If you are using 1.9.2 you could use each_with_object either with a string as on object or an array that you could join before returning it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top