2009-07-31 269 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)