使用accepts_nested_attributes_for时如何防止模型中出现重复数据?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果确实应该只有一门“数学”课程,我建议在课程模型上使用 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").