Mary Dear
Mary Dear

Reputation: 185

undefined method `some_method' for "some_variable":String. Ruby on Rails

I'm trying to I'm trying to show table, but I get an error undefined method `name' for "Sphere Kharkov":String This is my Instance Variables:

@result1 {"No department"=>"1", "Dep2"=>"1", "Sphere Kharkov"=>"2"}

@result2 {"Sphere Kharkov"=>"1"}

@department_names ["Sphere Kharkov", "Dep2", "Dep without members", "No department"]

Controller's methods

def age_profile
    @result1 = age_report(1,9)
    @result2 = age_report(10, 12)
    @department_names = current_company.departments.map(&:name)
    @department_names << "No department"
  end

def age_report(start_age, end_age)
      result = {}
      User.select("COALESCE(departments.name, 'No department') AS name, COALESCE(count( * ), '0') AS count")
      .joins("LEFT JOIN departments ON departments.id = users.department_id")
      .where(:users => { :is_deleted => 0, :company_id => current_company.id})
      .where("TIMESTAMPDIFF(YEAR, `date_of_birth`, CURDATE()) BETWEEN :start_age AND :end_age", start_age: start_age, end_age: end_age)
      .group("departments.name")
      .each {|d| result[d.name] = d.count }
      result
    end

In View:

%table.table.table-striped.table-bordered
  %tr
    %th= t('Depatment')
    %th= t('1-18')
    %th= t('18-25')
    %th= t('25-45')

  -@department_names.each do |f|
    %tr
      %td= f.name
      %td= @result1[f.name]
      %td= @result2[f.name]

Сould you help me please. What's wrong?

Upvotes: 1

Views: 139

Answers (2)

Marek Lipka
Marek Lipka

Reputation: 51191

@department_names variable contain strings that don't respond to name method. Simple solution is:

- @department_names.each do |f|
  %tr
    %td= f
    %td= @result1[f]
    %td= @result2[f]

Upvotes: 1

Arjan
Arjan

Reputation: 6274

This line:

 @department_names = current_company.departments.map(&:name)

Retrieves only the names of the companies. So basically you are calling the name method on the result of the name method.

So either remove .map(&:name) or just use f insteaf of f.name.

Upvotes: 1

Related Questions