Question

How would one iterate through a collection and output an attribute in one line in ERB?

I've tried the following, but that outputs the whole object:

<%= Post.all.each {|p| (content_tag :div, p.title)} %>
Was it helpful?

Solution

As @nmeylan pointed that calling Post.all in view is not a good practice.

I would use @posts as example below. You could try:

<%= @posts.map { |p| content_tag :div, h(p.title) }.join.html_safe %>

Since rails 4 escape HTML by default, you have to call html_safe or raw. But it seems like p.title is a user input, so it has to be escaped.

OTHER TIPS

First, you are calling an ActiveRecord method (Post.all) in your view, it's a bad practice, call it in your controller.

Then, to answer your question I would use the content_tag_for method or div_for

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