I\'m trying my best to build a helper that outputs a <\'ul> consisting of all the members of a collection. For each member of the collection I want to print out a <\'
@Joe,
You can still use your method display_all(collection_sym)
Just use:
return html.html_safe
instead of:
return html
I still find that in many situations, it is better to generate HTML from helpers, instead of using partials. So the html_safe
function in Rails 3 will make sure that you generate HTML, instead of converting it to String
.
I agree with the comment above recommending the use of a partial... but if you DID need to do this in a helper, this is a cleaner way to implement:
def display_all(collection)
content_tag(:ul, class: "list") do
collection.collect do |member|
concat(content_tag(:li, id: member.name.gsub(' ', '-').downcase.strip) do
member.name
end)
end
end
end
I'd pass in a collection explicitly rather than passing in a symbol to create a collection so you aren't always required to display ALL the records in a particular table at once. You could add pagination, etc.
As @TheDelChop says, you need a concat
for the inner content_tag
, otherwise the output is just <ul></ul>
Here's what that looks like:
def display_all(collection)
content_tag(:ul, :class => "list") do
collection.collect do |member|
concat(
content_tag(:li, :id => member.name.gsub(' ', '-').downcase.strip) do
member.name
end
)
end
end
end
More explanation here: Nesting content_tag in Rails 3