views:

450

answers:

3

I have a user who owns many phones
I have a a phone which has many call summaries
therefore my user has many call summaries

Now to the code that I have:

class User < ActiveRecord::Base
    has_many :phones
    has_many :call_summaries, :through => :phones
end  

class Phone < ActiveRecord::Base
    belongs_to :user
    has_many :call_summaries
end

class CallSummary < ActiveRecord::Base
    belongs_to :phones
end

I would like to generate a report that shows all the call summaries for the phones that belong to that certain user. I go into the controller and this is my code there:

def index
  @phones = Phone.find(:all, :conditions => ["user_id = ?", @current_user.id])
  @call_summaries = @phones.call_summaries.find(:all)
end

But this is returning this error:

undefined method `call_summaries' for #Array:0x476d2d0

Any help would be very much appreciated.

+2  A: 

@phones is an array of Phone objects. You have to iterate through that array and add each phone's call summaries to a single array. Try this:

@phones = Phone.find(:all, :conditions => ["user_id = ?", @current_user.id])
@call_summaries = @phones.inject([]){|arr, phone| arr + phone.call_summaries}
Pesto
+3  A: 

If you have the has_many :through relationship set up, you should just be able to do:

@call_summaries = @current_user.call_summaries

The problem with your method is that you're calling call_summaries on the @phones collection, rather than on individual phone instances.

Greg Campbell
Ah this worked, thanks. Just one more thing, I set up a foreign key in call_summaries because the column names are different. And I am not looking for the phones.id column either. I am looking for a generated hex key. This is the SQL that is generated from the correct command with a foreign key:SELECT call_summaries.* FROM call_summaries INNER JOIN phones ON call_summaries.reported_by = phones.id WHERE phones.user_id = 1It should be phones.hex_key instead of phones.id. How do I change that, I tried foreign keys but unless i did something dumb, that didn't work. Thanks again!
Ryan
It sounds like you'll need to use the :foreign_key and :primary_key options on both ends of the association. In CallSummary, for instance, try `belongs_to :phone, :foreign_key => :reported_by, :primary_key => :hex_key` (and do the same thing for the has_many association in Phone).
Greg Campbell
A: 

Off topic and just me being fussy, but a dynamic finder is more readable:

@phones = Phone.find_all_by_user_id(@current_user)
askegg