mysql - 如何在 has_and_belongs_to_many Rails 中创建联接表记录

标签 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方法,它应该做的是

为每个学生在 Students_teachers 中添加一行,其中 student_id = currentstudentidteacher_id=count

countdistribute_each 中的变量

最佳答案

这看起来像是从 TeacherStudent 的随机分布,但您应该可以通过找到 Teacher 对象来简单地做到这一点并将其分配给教师,如下所示

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

这当然假设你所有的老师都是连续编号的(Rails不能保证,而且鉴于这种方法,肯定会有老师很快退出学生分布:-)。更好的解决方案是在循环之前获取所有教师并使用数组。这将使您不必在每个循环中再进行一次数据库调用。这会让它像

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

关于mysql - 如何在 has_and_belongs_to_many Rails 中创建联接表记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24318427/

相关文章:

mysql - 如何将年份与时间戳日期进行比较

mysql - 无法添加外键约束MySql

mysql - 搜索按钮不起作用,它说没有选择数据库,如何解决这个问题?

mysql - 如何在XAMPP中编辑phpmyadmin中的触发器?

php - 使用 mysql php session 进行 LDAP 身份验证

ruby-on-rails - 在 factory_girl 定义中指定一个随机关联对象

python - SQLite 值错误 : parameters are of unsupported type

SQL:从两个表查询,不能将组保留在单行中

ruby-on-rails - rails - 查找具有重复属性的对象

ruby-on-rails - 使用 authlogic 登录时调用 current_user 的方法