2011-08-27 112 views
1

我有一個rails 3應用程序。ActiveRecord查詢問題

我有以下情況:有學生和老師誰有互動。基於這些相互作用中的一些,教師可以選擇給學生獎勵,即學生報告。

class Student 
has_many :interactions 
has_many :teachers, :through=>:interaction 

class Teacher 
has_many :interactions 
has_many :students, :through=>:interaction 
has_many :rewards 

class Interaction 
belongs_to :teacher 
belongs_to :student 
has_many :student_rewards 
has_many :rewards, :through=>:student_reward 

class Reward 
belongs_to :teacher 
has_many :student_rewards 

class StudentRewards 
belongs_to :reward 
belongs_to :interaction 

This is a crude ERD diagramof the data

如何將專家碼的有效途徑,以獲取所有學生的教師有很多,並非一定那些學生已經贏得了],並列出對在教師信息的獎勵顯示?

我試過了,但是我必須在視圖中分別獲取教師信息,這很糟糕。 (假設student_id數據= 1):

@rewards = Reward.joins(:teacher => :interactions) 
       .where("interactions.student_id=1") 
       .paginate(:page => params[:page], :per_page => 5) 

問題:

  1. 這是做的最好的方法是什麼?
  2. 當我在視圖中遍歷這個時,我必須發出額外的查詢來顯示關於教師[名字,deomographics]的信息。我怎樣才能更有效地獲取?

我希望能夠做到這一點:

<% for reward in @rewards%> 
    <%= reward.name, reward.teacher.name, reward.teacher.bio%><br> 
<%end%> 

回答

0

如果有學生,然後讓該學生的老師的獎勵是很容易,像這樣獲得的:

@student = Student.find(1) 
@rewards = [] 
@rewards += @student.teachers.collect {|teacher| teacher.rewards } 

的你在學生has_many :teachers, :through=>:interaction中設定的關係使這成爲可能。