2011-05-17 29 views
0

一個問題,我有一個問題有關:的Rails 3:有關數組

@st = exam.students.find(:all) 
@st.each do |student| 

返回我的數組與所有的學生,但:

exam.students.each do |student| 

返回我的陣列,4次,每次學生

這裏是一個打印

print

任何人都有這個想法?

UPDATE:

這裏是我的考試模式:

set_table_name "exam" 
set_primary_key "ID_Exam" 

belongs_to :questionnaire, :foreign_key => "ID_Questionnaire" 

has_many :responses, :foreign_key => "ID_Exam" 
has_many :students, :through => :responses, :foreign_key => "ID_Exam", :group => "response.ID_Student" 

belongs_to :professor, :foreign_key => "ID_Professor" 

has_many :student_exam_times 
has_many :exam_halted_students 
has_many :exam_paused_students 
has_many :answered_questions 

而且這是我的學生模型:

set_table_name "student" 
set_primary_key "ID_Student" 

has_one :user, :foreign_key => "ID_User" 

has_many :group_student, :foreign_key => "ID_Student", :group => "group_student.ID_Group" 
has_many :groups, :through => :group_student, :foreign_key => "ID_Group" 

has_many :responses, :foreign_key => "ID_Student" 
has_many :exams, :through => :responses, :foreign_key => "ID_Exam", :group => "exam.ID_Exam" 

has_many :student_exam_times 
has_many :exam_halted_students 
has_many :exam_paused_students 
has_many :marked_questions 
has_many :answered_questions 

has_many :messages, :order => "viewed ASC, send_at DESC" 

更新2:

這裏是我的塊:

students_exam = exam.students.find(:all) 
    students_exam.each do |student| 
     cont=StudentExamTime.find(:first,:conditions => {:student_id => student.id, :exam_id => params[:exam_id].to_i }) 
     bd_time=0 
     if cont==nil 
     cont=StudentExamTime.new 
     else 
     bd_time=cont.time 
     end 
     cont.student_id=student.id 
     cont.exam_id=params[:exam_id].to_i 
     cont.time=bd_time + params[:time].to_i 
     cont.save 
    end 
+0

這是奇怪的,這是什麼'exam.students.count'說? – sled 2011-05-17 18:49:01

+0

嗨,thx爲您的迴應。 exam.students.count返回12和3 for exam.students.find(:all) – 2011-05-17 19:11:28

+0

您好,您可以在檢查模型中發佈'has_many'關聯嗎?並用mysql管理控制檯檢查你的數據庫表。 – sled 2011-05-17 19:17:56

回答

1

添加:uniq => true

has_many :students, :through => :responses, :foreign_key => "ID_Exam", :group => "response.ID_Student" 

在考試模式

+0

謝謝,它工作正常!你有一個解釋爲什麼沒有「:uniq => true」exam.students返回每個學生4次? – 2011-05-17 20:07:32

+0

uniq做了什麼是它增加了不同的選擇查詢。基於連接的查詢不僅返回uniq行,而且返回所有符合條件的行。 – 2011-05-17 20:12:04

+0

好的謝謝,謝謝大家! – 2011-05-17 20:16:51

0

您可以在考試模型中發佈關係嗎?

我最初的感覺是,考試和學生之間的關係可能會比「典型」聲明更受歡迎。

0

貌似exam.students將返回每個學生與之相關的考試(甚至重複)

exam.students.find(:all)將返回唯一的學生名單。

你的模型關係和你的表格設置是什麼樣的?

0

我懷疑內

exam.students.each do |student| 

您塊回國的4名學生的陣列。你可以發佈該塊嗎?