2009-07-31 232 views
5

未定義的方法我有誰擁有許多手機用戶
我有有許多呼叫摘要AA電話
因此我的用戶有很多呼叫摘要紅寶石數組

現在給我的代碼:

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 

我想生成一個報告,顯示屬於該特定用戶的電話的所有呼叫摘要。我去到控制器,這是我的代碼有:

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

但這返回此錯誤:

undefined method `call_summaries' for #Array:0x476d2d0

任何幫助將是非常讚賞。

回答

5

如果您擁有的has_many:通過關係成立,你應該能夠做到:

@call_summaries = @current_user.call_summaries 

與方法的問題是,我們在調用call_summaries上@phones集合,而不是單個電話實例。

+0

啊,這工作,謝謝。還有一件事,我在call_summaries中設置了一個外鍵,因爲列名是不同的。而且我也不在尋找phones.id專欄。我正在尋找一個生成的十六進制密鑰。這是從正確的命令與外鍵生成的SQL: SELECT call_summaries * FROM call_summaries INNER JOIN手機ON call_summaries.reported_by = phones.id WHERE phones.user_id = 1 應該phones.hex_key而不是phones.id。我如何改變這一點,我嘗試了外鍵,但除非我做了一些愚蠢的事情,那沒有用。 再次感謝! – Ryan 2009-07-31 18:30:10

+0

聽起來你需要在關聯的兩端使用:foreign_key和:primary_key選項。例如,在CallSummary中,嘗試`belongs_to:phone,:foreign_key =>:reported_by,:primary_key =>:hex_key`(併爲Phone中的has_many關聯做同樣的事情)。 – 2009-07-31 19:40:54

2

@phonesPhone對象的數組。您必須遍歷該數組,並將每個電話的調用摘要添加到單個數組。試試這個:

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

題外話,只是我被挑剔,而是一個動態取景器是更具可讀性:

@phones = Phone.find_all_by_user_id(@current_user)