我正在用 Ruby on Rails 构建的博客应用程序的主页上显示最近的评论。我想限制评论表的
body
列中显示的字符数。
我假设我可以在
<%=h comment.body %>
的代码末尾添加一些内容,但我还不知道那会是什么,因为我对 Ruby 和 Rails 都是新手。
这是我在
/views/posts/index.html.erb
文件中的代码:
<% 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 -%>
尝试截断视图助手
<%=h truncate(comment.body, :length => 80) %>
我刚刚找到了另一种方法(如果你不想添加“...”)
<%= comment.body.first(80) %>
如字符串RoR API 中所述:
首先(限制= 1)
返回第一个字符。如果提供了限制,则返回从字符串开头开始的子字符串,直到达到限制值。如果给定的限制大于或等于字符串长度,则返回 self。
comment = "1234567890"
comment.first(5)
# => "12345"
comment.first(10)
# => "1234567890"
comment.first(15)
# => "1234567890"
如果您使用
rails 4.2
或以上,那么您可以使用truncate_words
方法。例如:
“在一个一切都很棒的世界”.truncate_words(3)输出:“在一个世界中......”
如果你想限制字符数,也可以使用
truncate
方法。
<%= "#{message.truncate(charcount)}" %>