5

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.

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 = 1 It 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!
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).
2

@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}

Comments

1

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

@phones = Phone.find_all_by_user_id(@current_user)

1 Comment

should be @phones = Phone.find_all_by_user_id(@current_user.id)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.