2015-08-19 71 views
2

我正在为一个旧的应用程序添加一个功能,这个功能并非由我自己制作,而且这对于RoR来说相对较新,这对我来说会造成一些困惑。如何访问模型的孩子的其他父母

我叫机型reponseactivity_pointreport

response有两个家长,它belongs_to的activity_pointreport

我试图访问activity_points一个DO块,像这样:

report.responses.activity_points.activity.each do |a| 

显然,这是行不通的。我收到错误消息:

undefined method `activity_points' for []:ActiveRecord::Relation 

感谢任何人可以帮助我解决这个小问题。

+0

什么是活动? – Swards

回答

3

或者,您可以添加这样的事情你的报表模型

has_many :responses 
has_many :activity_points, :through => :responses 
has_many :activities, :through => :activity_points 

,那么你可以做到这一点

report.activities.each do |a| 

另一种方式做这种事情,添加一个方法来报告并从另一侧加入(以获得活动对象)

def activities 
    Activity.joins(:activity_points => :responses).where('responses.report_id = ?', id) 
end 

做这一切的重点,如果你不需要,你不想创建Ruby对象。嵌套循环也是独特项目和排序的潜在问题。

1

每个response有几个activity_points所以你应该重复通过responses。同样,每个activity_point有几个activities,所以:

report.responses.each do |r| 
    r.activity_points.each do |ap| 
    ap.activity.each do |a| 
     # Do your thing 
    end 
    end 
end 
1

首先,当你写report.responses,这将返回ActiveRecord array。由于activity_points对于arrays是未定义的方法,因此无法调用它。所以要调用此方法有两个条件:

  1. 您必须告诉您的应用程序将调用该数组的哪个元素将调用该方法。例如,report.responses.first.activity_pointsreport.responses.second.activity_points ...
  2. Response模型必须有一个has_many: activity_points才能调用此方法。
0

您仍然可以使用循环,但这将需要多次数据库调用。因此,我的解决方案涉及直接数据库调用的效率。

Activity.includes(activity_point: {responses: :report}).where(reports: {id: report.id}).each do |a| 
    #... 
    #... 
end 
相关问题