bgadoci bgadoci - 1 year ago 85
Ruby Question

Limiting characters/words in view - ruby on rails

I am displaying recent comments on the home page of a very simple blog application I am building in Ruby on Rails. I want to limit the number of characters that are displayed from the 'body' column of the comments table. I am assuming I can just add something to the end of the code for <%=h comment.body %> but I don't know what that would be yet as I am new to both Ruby and Rails.

Here is the code I have in the /views/posts/index.html.erb file:

<% Comment.find(:all, :order => 'created_at DESC', :limit => 5).each do |comment| -%>
<%=h %> commented on
<%= link_to h(, %><br/>
<%=h comment.body %>
<i> <%= time_ago_in_words(comment.created_at) %> ago</i>
<% end -%>

Answer Source

Try the truncate view helper

<%=h truncate(comment.body, :length => 80) %>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download