简体   繁体   English

如何在Rails中查找字符串长度?

[英]How to find string length in Rails?

First of all I am brand new to ruby, so forgive me for being a noob. 首先,我是红宝石的新手,所以请原谅我是菜鸟。 There is a section on my site where users can add comments. 我的网站上有一个部分,用户可以在其中添加评论。 Looking through the controller folder, I found a comments_controller.rb file. 浏览controller文件夹,发现一个comments_controller.rb文件。 In that file there is a variable @comment . 在该文件中,有一个@comment变量。 I want to display the length of whatever comment the user adds on my show.html.erb file. 我想显示用户在show.html.erb文件上添加的任何注释的长度。 (this is the page where comments are displayed). (这是显示评论的页面)。 From my very limited understanding of Rails, I have tried to put <%= @comment.length %> into my show.html.erb file, but I get a NoMethod error. 从对Rails的了解非常有限,我尝试将<%= @comment.length %>放入show.html.erb文件中,但出现NoMethod错误。 I have no idea what to do, someone please help! 我不知道该怎么办,请有人帮忙!

Am I looking at the right section? 我在看正确的部分吗?

Your @comment returns an instance of Comment model, which is not a string and doesn't have length method defined on it. 您的@comment返回Comment模型的实例,该实例不是字符串,并且没有定义length方法。 You are looking to measure an attribute of that model. 您正在寻找测量该模型的attribute So, first find out which attribute you are interested in and then call length on that attribute. 因此,首先找出您感兴趣的属性,然后在该属性上调用length

Eg @comment.body.length . 例如@comment.body.length

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

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