Michaël
Michaël

Reputation: 1130

Rails 3: A question about array

I've a question about that:

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

Return me an array with all student, but:

exam.students.each do |student|

Return me an array with 4 times each students

Here is a print

print

Anyone have an idea about that?

UPDATE:

Here is my Exam Model:

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

And this my Student Model:

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"

UPDATE 2:

Here is my block:

    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

Upvotes: 0

Views: 132

Answers (4)

Aj Gu
Aj Gu

Reputation: 1439

Add :uniq => true

to

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

in your exam model

Upvotes: 1

Addy
Addy

Reputation: 1851

I have a suspicion your block within

exam.students.each do |student|

is returning an array of 4 students. can you post that block too.

Upvotes: 0

Jimmy
Jimmy

Reputation: 9815

Looks like exam.students is returning every student with that associated exam (even duplicates)

Whereas exam.students.find(:all) is returning a list of unique students.

What does your model relation look like and your table setup?

Upvotes: 0

twmills
twmills

Reputation: 3015

Can you post the relationships in your Exam model?

My initial feeling is that you have more-complex-than-typical relationship between exam and students that could benefit from a "DISTINCT" declaration.

Upvotes: 0

Related Questions