1

我正在尝试我正在尝试显示表格,但我得到一个错误 undefined method `name' for "Sphere Kharkov":String 这是我的实例变量:

@result1 {"无部门"=>"1", "Dep2"=>"1", "Sphere Kharkov"=>"2"}

@result2 {“球体哈尔科夫”=>“1”}

@department_names [“Sphere Kharkov”,“Dep2”,“没有成员的Dep”,“没有部门”]

控制器的方法

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

在视图中:

%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]

你能帮我吗?怎么了?

4

2 回答 2

1

这一行:

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

仅检索公司的名称。所以基本上你是在 name 方法的结果上调用 name 方法。

所以要么删除.map(&:name),要么只使用finsteaf of f.name

于 2013-10-15T13:27:46.780 回答
1

@department_names变量包含不响应name方法的字符串。简单的解决方案是:

- @department_names.each do |f|
  %tr
    %td= f
    %td= @result1[f]
    %td= @result2[f]
于 2013-10-15T13:29:53.097 回答