简体   繁体   English

在Rails中进行字符串插值

[英]Doing String interpolation in rails

How can I print the no:of comments to a particular post under it in rails? 我如何在rails下的特定帖子上打印no:of评论?

<%=@post.comments.any? ? " " : "No comments yet!!" %> 

This is what I have done. 这就是我所做的。 Instead, if there are any comments for a particular post, I want to display it like "There are 5 comments" or something. 相反,如果对某个特定帖子有任何评论,我想显示为“有5条评论”之类的内容。

pls help. 请帮助。

Just print the number of comments: 只需打印评论数:

<%= @post.comments.any? ? "#{@post.comments.size} comments" : "No comments yet!!" %>

NOTE 1: You can also use Rails helper for printing pluralized strings using pluralize : 注意1:您也可以使用Rails helper使用pluralize打印多个字符串:

<%= @post.comments.any? ? pluralize(@post.comments.size, "comment") : "No comments yet!!" %>

NOTE 2: Also, use .size instead of .count . 注意2:此外,请使用.size而不是.count Because size will count number of elements in your collection, whereas count will hit the database and count the rows in the database. 因为size将计算集合中元素的数量,而count将影响数据库并计算数据库中的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM