限制视图中的字符/单词 - ruby on rails
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2633130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Limiting characters/words in view - ruby on rails
提问by bgadoci
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.
我正在用 Ruby on Rails 构建的一个非常简单的博客应用程序的主页上显示最近的评论。我想限制从评论表的“正文”列显示的字符数。我假设我可以在 <%=h comment.body %> 的代码末尾添加一些东西,但我不知道那会是什么,因为我是 Ruby 和 Rails 的新手。
Here is the code I have in the /views/posts/index.html.erb file:
这是我在 /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 -%>
回答by maxhm10
I just found another way (if you don't want to add the "...")
我刚刚找到了另一种方法(如果您不想添加“...”)
<%= comment.body.first(80) %>
As said in the RoR API for String:
first(limit = 1)
Returns the first character. If a limit is supplied, returns a substring from the beginning of the string until it reaches the limit value. If the given limit is greater than or equal to the string length, returns self.
第一(限制= 1)
返回第一个字符。如果提供了限制,则从字符串的开头返回一个子字符串,直到达到限制值。如果给定的限制大于或等于字符串长度,则返回 self。
comment = "1234567890"
comment.first(5)
# => "12345"
comment.first(10)
# => "1234567890"
comment.first(15)
# => "1234567890"
回答by jain77
If you are using rails 4.2or above then you can use truncate_wordsmethod.
如果您正在使用rails 4.2或以上,那么您可以使用truncate_words方法。
For example:
"In a world where everything is awesome".truncate_words(3)Output: "In a world..."
例如:
“在一个一切都很棒的世界中”.truncate_words(3)输出:“在一个世界中……”

