Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1.4 - Render :text

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>
like image 305
oprogfrogo Avatar asked Mar 30 '12 00:03

oprogfrogo


3 Answers

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."
like image 169
Fellow Stranger Avatar answered Nov 18 '22 20:11

Fellow Stranger


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

  • https://github.com/drapergem/draper
like image 25
scarver2 Avatar answered Nov 18 '22 20:11

scarver2


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.

like image 2
John Avatar answered Nov 18 '22 20:11

John