bgadoci bgadoci - 5 months ago 22
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| -%>
<p>
<%=h comment.name %> commented on
<%= link_to h(comment.post.title), comment.post %><br/>
<%=h comment.body %>
<i> <%= time_ago_in_words(comment.created_at) %> ago</i>
</p>
<% end -%>

Answer

Try the truncate view helper

<%=h truncate(comment.body, :length => 80) %>