Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Undefined method `truncate' in model

I have the following method in my model which crops the record's description, but for an unknown reason the truncate method does not work:

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

Anyone sees what I'm doing wrong? Thanks.

like image 280
actaram Avatar asked Mar 14 '15 23:03

actaram


3 Answers

You're using it wrong, you should be calling this method on a String. See truncate's signature.

Use:

if description.length > nb_words_max
  description.truncate(nb_words_max, :separator => ' ') + " ..."
else
  ...
like image 123
vee Avatar answered Sep 23 '22 18:09

vee


In rails include:

 include ActionView::Helpers::TextHelper

but if you want to tested in Ruby irb:

 require 'action_view'
 include ActionView::Helpers::TextHelper 
like image 42
Papaya Labs Avatar answered Sep 20 '22 18:09

Papaya Labs


The truncate method you're looking for is a view helper so it won't be available inside your model method, you should be calling truncate from inside a view. Also, if view helper will adding ellipses for you so you can just say:

<%= truncate(m.description, :length => 500, :separator => ' ') %>
like image 43
mu is too short Avatar answered Sep 19 '22 18:09

mu is too short