模型中未定义的方法`truncate’
我在我的模型中有以下方法来裁剪记录的描述,但由于未知原因,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
有人看到我做错了吗? 谢谢。
你使用它错了,你应该在String
上调用这个方法。 请参见truncate
的签名。
使用:
if description.length > nb_words_max description.truncate(nb_words_max, :separator => ' ') + " ..." else ...
在rails中包括:
include ActionView::Helpers::TextHelper
但如果你想在Ruby irb中测试:
require 'action_view' include ActionView::Helpers::TextHelper
您正在寻找的truncate
方法是一个视图助手,因此它在模型方法中不可用,您应该从视图内部调用truncate
。 另外,如果视图帮助器会为您添加省略号,那么您只需说:
<%= truncate(m.description, :length => 500, :separator => ' ') %>