学生可以有很多老师,老师可以有很多学生。
此关联在此处定义很好:
#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
我如何使用distribute_students方法,它应该做什么
为每位学生在student_teachers中添加一行student_id = currentstudentid
和teacher_id=count
count
是distribute_each
答案 0 :(得分:2)
这似乎是从Teacher
到Student
的随机分布,但您应该能够通过查找Teacher
对象并将其分配给{{1}来完成此操作在
teachers
当然假设您的所有my_teacher = Teacher.find(count)
student.teachers << my_Teacher
都是连续编号的(Teacher
不保证,并且鉴于此Rails
分发方法,必然会有很快退出的教师: - )。更好的解决方案是在循环之前获取所有教师并使用数组。这样可以避免在每个循环中再进行一次数据库调用。这会使它像
Student