模型中未定义的方法`truncate'

act*_*ram 4 ruby ruby-on-rails

我在我的模型中有以下方法来裁剪记录的描述,但由于未知原因,truncate方法不起作用:

def cropped_description
  nb_words_max = 500
  if description.length > nb_words_max
    truncate(description, :length => nb_words_max, :separator => ' ') + " ..."
  else
    description
  end
end
Run Code Online (Sandbox Code Playgroud)

有人看到我做错了吗?谢谢.

vee*_*vee 9

你使用它错了,你应该在a上调用这个方法String.见truncate签名.

使用:

if description.length > nb_words_max
  description.truncate(nb_words_max, :separator => ' ') + " ..."
else
  ...
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢,这就是我一直在寻找的答案.虽然,你应该删除`:length =>`,因为它会产生一个错误:`Fixnum与Hash的比较失败',因为`length`不是方法选项的一部分. (2认同)

Pap*_*abs 6

在导轨中包括:

 include ActionView::Helpers::TextHelper
Run Code Online (Sandbox Code Playgroud)

但是如果你想在 Ruby irb 中测试:

 require 'action_view'
 include ActionView::Helpers::TextHelper 
Run Code Online (Sandbox Code Playgroud)