views:

19

answers:

3

I've got following method in User model

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

This is what the console prints when I call this method:

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

however, the following code does not work:

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

What do I need to do in order to get the first_name of the employees from the loop?

A: 

Looks to me that the variable i is still an array. You declare @employee as an empty array and you insert another array which is what is returned by Group.find(i).employees.

i[0] should contain:

#<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">
Hugo
A: 

The Group.find(i).employees call returns an array, so your get_employees method is returning an array of arrays. Replacing the last line of get_employees with @employees.flatten! should do the trick.

sluukkonen
A: 

As the previous poster noted, you've got an array within an array. Why recreate some logic that is already built into rails? I would have done something like this in the user model:

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

Then you can just do User.employees

Beerlington
I can not do this...because the way I am getting groups in User model is: `has_many :departments has_many :groups, through => :departments` now I can not do `has_many :employees, :through => :groups`
Omnipresent
there is a similar question along this type of model on SO: http://stackoverflow.com/questions/3568528/how-to-manage-3-many-to-many-models-in-rails
Omnipresent