Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 限制视图中的字符/单词-ruby on rails_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 限制视图中的字符/单词-ruby on rails

Ruby on rails 限制视图中的字符/单词-ruby on rails,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在用RubyonRails构建的一个非常简单的博客应用程序的主页上显示最近的评论。我想限制注释表“body”列中显示的字符数。我假设我可以在的代码末尾添加一些东西,但我不知道会是什么,因为我对Ruby和Rails都是新手 以下是我在/views/posts/index.html.erb文件中的代码: <% Comment.find(:all, :order => 'created_at DESC', :limit => 5).each do |comment| -%>

我正在用RubyonRails构建的一个非常简单的博客应用程序的主页上显示最近的评论。我想限制注释表“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 -%>
'created_at DESC',:limit=>5)。每个do | comment |-%>

评论

以前

尝试查看帮助程序

<%=h truncate(comment.body, :length => 80) %>
80)%>
我刚刚找到了另一种方法(如果您不想添加“…”)


如果您使用的是
rails4.2
或更高版本,则可以使用
truncate\u words
方法。

例如:
“在一个一切都很棒的世界里”。删去单词(3)

输出:“在一个世界上……”


如果要限制字符数,还可以使用
truncate
方法。我用它来在引导行中显示足够多的字符,以便在某种程度上匹配同一行中显示的图像的高度

<%= "#{message.truncate(charcount)}" %>


只是好奇(不是Rails用户):这也行吗?这与truncate在下面所做的差不多,但它也会检查长度,以确定是否要在末尾添加“…”只是想添加truncate不是多字节安全的(ruby 1.8,rails 2.3.5,不确定ruby 1.9)。它在指定的字节处截断,如果您有unicode字符串,则输出将更短(少于指定的长度)。你也可能会在结尾出现一个破碎的角色。当然,如果您使用ASCII或任何其他8位字符编码,则无需担心。开头的“h”是什么意思?或者这是一个拼写错误?@ProGrammar它不是一个拼写错误,因为它被多次使用;但是我想知道它是不是一个我应该知道的内置工具(比如
j
javascript
escape助手的缩写)喜欢这个。谢谢如果文本中还包含html标记,则不需要包含任何Rails视图帮助程序即可使用它。attach.html\u safe
comment = "1234567890"

comment.first(5)
# => "12345"

comment.first(10)
# => "1234567890"

comment.first(15)
# => "1234567890"
<%= "#{message.truncate(charcount)}" %>