mysql - How to create join table records in has_and_belongs_to_many rails -



mysql - How to create join table records in has_and_belongs_to_many rails -

students can have many teachers , 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 pupil < 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 |student| # todo: count count += 1 count = 0 if count >= teacher.count + 1 end end end

how can utilize distribute_students method, should

for each pupil add together row in students_teachers student_id = currentstudentid , teacher_id=count

count beingness variable in distribute_each

that seems random distribution teacher student, should able finding teacher object , assigning teachers in

my_teacher = teacher.find(count) student.teachers << my_teacher

which of course of study assumes teachers numbered consecutively (which rails not guarantee , there bound teachers quit given method of student distribution :-). improve solution fetch teachers before loop , work array. save going through 1 more database phone call in every loop. create like

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

mysql sql ruby-on-rails ruby activerecord

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -