如何在has_and_belongs_to_many rails中创建连接表记录

时间:2014-06-20 00:49:56

标签: mysql sql ruby-on-rails ruby activerecord

学生可以有很多老师,老师可以有很多学生。

此关联在此处定义很好:

#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 = currentstudentidteacher_id=count

countdistribute_each

中的变量

1 个答案:

答案 0 :(得分:2)

这似乎是从TeacherStudent的随机分布,但您应该能够通过查找Teacher对象并将其分配给{{1}来完成此操作在

teachers

当然假设您的所有my_teacher = Teacher.find(count) student.teachers << my_Teacher 都是连续编号的(Teacher不保证,并且鉴于此Rails分发方法,必然会有很快退出的教师: - )。更好的解决方案是在循环之前获取所有教师并使用数组。这样可以避免在每个循环中再进行一次数据库调用。这会使它像

Student