0

我正在创建一个列出员工并使用自联接来显示经理和 direct_reports 的应用程序。

在我的模型中,我有:

has_many :direct_reports, :class_name => "Person", :foreign_key => "manager_id"
belongs_to :manager, :class_name => "Person"

在我看来,我试图链接到员工的所有 direct_reports,其中他们的姓名(分为 fname 和 lame)构成链接。

目前,在我看来,对于 direct_reports,我有以下 Rails 指南推荐的内容。

<%= @person.direct_reports %>

这导致生成这个。

    [#<Person id: 3674, fname: "Leland", lname: "Allison", phone: "8474020494", email: 
    "leland.allison@myco.com", ntid: "lalli", address: "3568 Sanders Rd.", city: 
    "Northbrook", state: "IL", zipcode: "60062", country: "USA", suite: nil, column: 
    nil, title: nil, department: nil, created_at: "2013-02-01 19:17:58", updated_at: 
    "2013-02-01 19:17:58", equipment: nil, capacity: nil, latitude: nil, longitude: 
    nil, manager: nil, direct_report: nil, manager_id: 3668>, #<Person id: 3685, fname:
     "Rochelle", lname: "Baldwin", phone: "8474020338", email: "rochelle.baldwin@myco.com",
     ntid: "rbald", address: "3412 Sanders Rd.", city: "Northbrook", state: "IL", 
    zipcode: "60062", country: "USA", suite: nil, column: nil, title: nil, department: 
    nil, created_at: "2013-02-01 19:17:58", updated_at: "2013-02-01 19:17:58", equipment: 
    nil, capacity: nil, latitude: nil, longitude: nil, manager: nil, direct_report: nil,
     manager_id: 3668>, #<Person id: 3692, fname: "Tammy", lname: "Barnett", phone: 
    "8474020275", email: "tammy.barnett@myco.com", ntid: "tbarn", address: "3349 
    Sanders Rd.", city: "Northbrook", state: "IL", zipcode: "60062", country: "USA", 
    suite: nil, column: nil, title: nil, department: nil, created_at: "2013-02-01 19:17:58",
     updated_at: "2013-02-01 19:17:58", equipment: nil, capacity: nil, latitude: nil, 
    longitude: nil, manager: nil, direct_report: nil, manager_id: 3668>]

所以我显然得到了每条记录的整个对象,这比我需要的要多。

我尝试将以下内容放在我的观点中:

<% @people.each do |person| %>
  <%= link_to person.lname + ", " + person.fname, person %>
<% end %>

但这行不通。我收到“nil:NilClass 的未定义方法‘每个’”错误。

有任何想法吗?

4

3 回答 3

1

您还没有定义@People,所以没有 each 。这将是@person.direct_reports.each

于 2013-02-01T21:52:49.057 回答
1

您应该将值保存在任何变量中,然后对其应用每个变量。没有@people变量定义,因此@people为零。

您的代码在控制器中将如下所示:

@people = @person.direct_reports  

并查看您的代码将如下所示:

 <% @people.each do |person| %>
        <%= link_to person.lname + ", " + person.fname, person %>
    <% end %>

现在可以使用

于 2013-02-01T21:55:54.840 回答
0

def people_and_reports(person)
  [person, person.direct_reports.map {|p| people_and_reports(p)}].flatten.uniq
end

@people = people_and_reports(@person)

哎呀..只是重读问题..这将递归地从一个人走到所有报告和报告报告。你可能只需要@people = @person.direct_reports

于 2013-02-01T21:58:48.170 回答