Rails helper to return <li> for each category actually returning hash of categories

StackOverflow https://stackoverflow.com/questions/21959646

  •  15-10-2022
  •  | 
  •  

I'm trying to clean up my views and be more DRY by using helpers. Starting with what seems like a simple one to return an li for each category.

def showcats
  Category.all.each do |cat|
    content_tag(:li, link_to(cat.title, cat))
  end
end

I've tried calling it in erb and haml using either

<%= showcats %>

or

= showcats

and each time I get back this mess when the page renders:

[#<Category id: 1, title: "First Category", description: "This is the description of the first category", created_at: "2014-02-18 02:05:37", updated_at: "2014-02-18 02:05:37">, #<Category id: 2, title: "Second Category", description: "This is the description of the second category", created_at: "2014-02-18 02:05:37", updated_at: "2014-02-18 02:05:37">,

and so on...

I've tried it with changing the showcats helper to require a variable, and passing that along, like "showcats(@categories)" but the same thing persists. If I put "return" in front of content_tag it will not show the hash of all categories, but it only returns a single category link, which I think is to be expected.

I've read quite a few questions on SO and other places around the web and I can't see where my mistake is. Any advice?

有帮助吗?

解决方案

The each function is returning all the categories. So change the each method to map instead.

其他提示

Replace showcats method as shown below:

def showcats
  Category.all.collect do |cat|
    content_tag(:li, link_to(cat.title, cat))
  end.join.html_safe
end

collect : Returns a new array with the results of running block once for every element in enum whereas,

each : Returns the object on which each is called.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top