使用accepts_nested_attributes_for时如何防止模型中出现重复数据?

发布于 2024-11-16 00:11:54 字数 975 浏览 2 评论 0原文

class Student < ActiveRecord::Base
  has_many :enrollments
  has_many :courses, :through => :enrollments
  accepts_nested_attributes_for :courses
end

class Course < ActiveRecord::Base
  has_many :enrollments
  has_many :students, :through => :enrollments
end

class Enrollment < ActiveRecord::Base
  belongs_to :student
  belongs_to :course
end

我目前在我的模型中有这种关联,并且我正在使用accepts_nested_attributes_for,但特别是ryanB的嵌套形式 https://github.com/ryanb /嵌套表单 现在,我正在以我的形式创建一个学生并添加课程,我创建学生 A,姓名:Ryan,然后创建课程:数学。现在我想创建学生 B,姓名:Frank,课程:数学。现在我的课程数据库正在创建两个数学行,但我希望它只有一个,这样我就可以引用数学课程中的所有学生。我该如何实现这个目标?

课程数据库现在看起来像这样

id: 1, name: Math
id: 2, name: Math

这是我的注册数据库的样子:

student_id: 1, course_id: 1
student_id: 2, course_id: 2

但我想要

student_id: 1, course_id: 1
student_id: 2, course_id: 1
class Student < ActiveRecord::Base
  has_many :enrollments
  has_many :courses, :through => :enrollments
  accepts_nested_attributes_for :courses
end

class Course < ActiveRecord::Base
  has_many :enrollments
  has_many :students, :through => :enrollments
end

class Enrollment < ActiveRecord::Base
  belongs_to :student
  belongs_to :course
end

I currently have that association in my model and I am using accepts_nested_attributes_for but specifically ryanB's nested form https://github.com/ryanb/nested_form
Right now I am creating a student in my form and adding the courses, I create Student A, name: Ryan and then create Course: Math. Now I want to create student B, Name: Frank and Course:Math. Right now my course db is creating two Math rows but I want it to only have one so that then I can reference all the students that are in the Math course. How do I accomplish this?

Courses db looks like this now

id: 1, name: Math
id: 2, name: Math

This is how my Enrollment DB looks like:

student_id: 1, course_id: 1
student_id: 2, course_id: 2

But I would like

student_id: 1, course_id: 1
student_id: 2, course_id: 1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风铃鹿 2024-11-23 00:11:54

如果确实应该只有一门“数学”课程,我建议在课程模型上使用 validates_uniqueness_of :name 。当您创建一个新学生并希望将其附加到(仅)“数学”课程时,请执行 Course.find_by_name("Math").students.create(:name => "Frank")。

If there really should only be one "Math" Course, I would suggest a validates_uniqueness_of :name on the Course model. When you create a new Student and you want it to be attached to the (only) "Math" Course, do Course.find_by_name("Math").students.create(:name => "Frank").

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文