Rails: Undefined Method 'Truncate' in Model

Rails: Undefined method `truncate' in model

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
...

Rails: Undefined method `truncate' for main:Object

I found the answer at the following discussion Undefined method `truncate' in model

I should have included the ActionView::Helpers::TextHelper in my rails console with the following command

include ActionView::Helpers::TextHelper 

Then I could call the truncate method.

truncate(string, length: 17, separator: ' ')
=> "this is a tesf..."

My understanding now is that with the include command, the methods from ActionView::Helpers::TextHelper are now available in the console. truncate method can be executed on text.

access truncate method in model method

main_text is nil that's why you are getting the error

undefined method 'truncate' for nil:NilClass

To make sure you handle the nil you can use safe navigation operator

"#{title} #{main_text&.truncate(120)}"

This will work on ruby 2.3+

If you are using ruby < 2.3 you can make use of

"#{title} #{main_text.try(:truncate, 120)}"

truncate method truncating at random(?) length

The escaped HTML chars are actually counted in the length. This includes the link and title of your article.

By defaut in Rails, the link to your article will be something like /articles/1. But if you use a gem like friendly_id which creates slugged URLs such as /some-slugged-article-title, each article link will have a different length. This is what creates this variation in the truncating length.

In order to split around 500 characters of the visible text, you'll need to add the length of your article's title in the length argument. You can do so with this:

<%= truncate(simple_format(article.content), length: 500 + article.title.length, separator: ".", escape: false, omission: "... #{link_to("Read More", article)}") %>

How use method 'truncate' in controller?

Truncate works for Strings, but you call it with an ActiveRecord::Relation. First you have to call .first on @masters (or something similar to select just one record) and then a String attribute like .full_name

@masters = truncate(
User.search_by_full_name(params[:full_name]).where(master: :true)
.first.full_name
, separator: '['
)

You can also call it on each record:

@masters = User.search_by_full_name(params[:full_name]).where(master: :true)
.map { |master|
truncate(master.full_name, separator: '[')
}

Ruby on Rails: undefined method for self action in model?

It should be Search not List

@lists = Search.text_search(params[:query])

Because you are using class Search in your search.rb



Related Topics



Leave a reply



Submit