How to prevent duplicate data in a model when using 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
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 开发者_如何学JAVAwant 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
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").
精彩评论