DmitrySharikov
DmitrySharikov

Reputation: 69

How use method 'truncate' in controller?

 class SearchingController < ApplicationController
  include ActionView::Helpers::TextHelper
  def index
    @masters = User.search_by_full_name(params[:full_name]).where(master: :true)
    @courses = Course.searching_courses(params[:course_title])
    @masters = truncate(@masters, separator: '[')
  end

end

This is my controller. He return error

undefined method `truncate' for ActiveRecord::Relation []

how resolve it? Thanks!

Upvotes: 1

Views: 1048

Answers (3)

iGEL
iGEL

Reputation: 17392

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: '[')
  }

Upvotes: 1

The Brofessor
The Brofessor

Reputation: 2391

The truncate method from ActionView::Helpers only works on strings.

@masters is an active record relational object, so the method won't work.

Upvotes: 1

jakenberg
jakenberg

Reputation: 2113

You're trying to apply the truncate method to an array, which won't work because truncate only works with strings.

You're issue really lies within the @masters property. You need to deduce it into whatever string you're trying to truncate.

Upvotes: 1

Related Questions