I'm updating my rails 2 apps to rails 3 and find that the use of 'render :text' does not behave the same anymore.
@results is an array. In my controller:
render :text => "<ul>#{@results}</ul>"
It's returning the whole array as a string rather than iterating through each value:
<ul>
["
<li>Steve</li>
", "
<li>John</li>
"]
</ul>
Worked fine in Rails 2.x but not in 3. How do I fix this?
I'm expecting a result of:
<ul>
<li>Steve</li>
<li>John</li>
</ul>
I know this question is for Rails 3.1.4 only.
But those who come here and are on a more recent version, starting with Rails 5.1 we'll do this:
render plain: "I'm like everyone else."
The string contains HTML tags so you will need to mark it as safe so that Rails doesn't escape the tags.
render :text => "<ul>#{@results}</ul>".html_safe
NOTE: Unless there is a valid reason to have HTML in your controller, I recommend moving the list items to a view.
6/23/2014 UPDATE: In retrospect, I don't like having this string parsing logic in the controller. The @results
suggests there is HTML embedded in an object somewhere. I recommend using a presentation object and call a method like @results.list
. The Draper gem is well-suited for this.
Cite
I would suggest doing the following instead of render :text
render :partial => "result", :collection => @results
and add the file: _result.html.erb with
<ul>
<%= result %>
</ul>
or even better if you can remove the li tags from @results
<ul>
<li><%= result %></li>
</ul>
The Rails 3 docs say render text should be used for NON HTML text, which does not fit your use case. Using render :partial :collection is a better and more rails 3 way to iterate through your list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With