MikaAK
MikaAK

Reputation: 2364

How to create join table records in has_and_belongs_to_many rails

Students can have many teachers and teachers can have many students.

This association works fine defined here:

#teacher.rb

class Teacher < ActiveRecord::Base
  has_and_belongs_to_many :students
  validates :email, uniqueness: true
end


#student.rb

class Student < ActiveRecord::Base
  has_and_belongs_to_many :teachers
  validates :email, format: /\A[\w-\.]+@([\w-]+\.)+[\w-]{2,4}\z/
  validates :email, uniqueness: true
  validates :age, numericality: { greater_than: 3 }

  def name
    "#{first_name} #{last_name}"
  end

  def age
    today = Date.today
    years_passed = today.years_ago(birthday.year).year
    today.month < birthday.month ? years_passed -= 1 : years_passed
  end

  def self.distribute_students
    count = 0

    Student.all.each do |student|
      # TODO: Count
      count += 1
      count = 0 if count >= Teacher.count + 1
    end
  end
end

How can I use my distribute_students method, what it should do is

for each student add a row in students_teachers where student_id = currentstudentid and teacher_id=count

count being the variable in distribute_each

Upvotes: 2

Views: 535

Answers (1)

Patru
Patru

Reputation: 4551

That seems like a somewhat random distribution from Teacher to Student, but you should be simply able to do it by finding your Teacher object and assigning it to the teachers as in

my_teacher = Teacher.find(count)
student.teachers << my_Teacher

which of course assumes that all your Teachers are numbered consecutively (which Rails does not guarantee and there are bound to be teachers who quit soon given this method of Student distribution :-). A better solution would be to fetch all teachers before the loop and to work with an array. That would save you from going through one more database call in every loop. That would make it something like

all_teachers = Teacher.all
Student.all.each do |student|
  count += 1
  count = 0 if count >= all_teachers.count
  student.teachers << all_teachers[count]
end

Upvotes: 2

Related Questions