【问题标题】:How to create join table records in has_and_belongs_to_many rails如何在 has_and_belongs_to_many rails 中创建连接表记录
【发布时间】:2014-06-20 00:49:56
【问题描述】:

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

这个关联在这里定义得很好:

#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 中的变量

【问题讨论】:

  • 我怀疑你想添加的不是一列,而是一行?而且我并不清楚teacher_id = count的含义。您想将学生平均分配给老师吗?因此,每个学生将只有一位老师
  • 是的,他们仍然只有一位老师。如何在teacher_students 中插入一行?因为有些学生没有老师。

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


【解决方案1】:

这似乎是从TeacherStudent 的随机分布,但您应该可以通过找到您的Teacher 对象并将其分配给teachers 来实现,如下所示

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

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

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

【讨论】:

    猜你喜欢
    • 2018-01-12
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 2011-05-21
    相关资源
    最近更新 更多