2010-08-28 72 views
0

我在User模型得到了下面的方法循環和在軌鑄造問題

def get_employees 
    @employees = [] 
     groups.each do |i| 
     @employees << Group.find(i).employees 
     end 
     @employees 
    end 

這是控制檯打印時我把這種方法:

> >> User.find(4).get_employees 
> => [[#<Employee id: 4, first_name: "test", last_name: "test1", 
> email_address: "[email protected]", 
> created_at: "2010-08-25 04:23:02", 
> updated_at: "2010-08-25 04:23:02">, 
> #<Employee id: 5, first_name: "hello", last_name: "hello1", email_address: 
> "[email protected]", created_at: 
> "2010-08-25 04:51:37", updated_at: 
> "2010-08-25 04:51:37">]] 

但是,下面的代碼做不工作:

>> @user.get_employees.each{|i| p i.first_name} 
NoMethodError: undefined method `first_name' for #<Class:0x9e372f0> 

我需要做什麼才能得到來自循環的employees的?

回答

0

Group.find(i).employees調用返回一個數組,所以你get_employees方法正在返回的數組的數組。用@employees.flatten!代替get_employees的最後一行應該有效。

0

在我看來,變量我仍然是一個數組。您將@employee聲明爲空數組,然後插入另一個由Group.find(i).employees返回的數組。

I [0]應該包含:

#<Employee id: 4, first_name: "test", last_name: "test1", 
> email_address: "[email protected]", 
> created_at: "2010-08-25 04:23:02", 
> updated_at: "2010-08-25 04:23:02">, 
> #<Employee id: 5, first_name: "hello", last_name: "hello1", email_address: 
> "[email protected]", created_at: 
> "2010-08-25 04:51:37", updated_at: 
> "2010-08-25 04:51:37"> 
0

正如前面的海報所說,你已經有了一個數組。爲什麼重新創建一些已經內置在rails中的邏輯?我會做這樣的事情在用戶模式:

class User < ActiveRecord::Base 
    has_many :groups 
    has_many :employees, :through => :groups 
end 

然後,你可以做User.employees

+0

我不能這樣做...因爲我越來越組用戶模型的方式是:'的has_many :部門has_many:組,通過=>:部門'現在我不能'has_many:employees,:through =>:groups' – Omnipresent 2010-08-28 21:34:10

+0

沿着這種類型的模型在SO上有類似的問題:http://stackoverflow.com /問題/ 3568528 /如何管理的-3-許多一對多的模型,在護欄 – Omnipresent 2010-08-28 21:36:17