学生和学生has_many课程的课程
如何使用json API更新course以将多名学生分配到一门课程
模型
class Course < ActiveRecord::Base
has_many :course_students
has_many :students, through: course_students
accepts_nested_attributes_for :course_students
end
class Student < ActiveRecord::Base
has_many :course_students
has_many :courses, through: course_students
end
class CourseStudent < ActiveRecord::Base
belongs_to :course
belongs_to :student
end控制器
class CoursesController < SessionsController
def update
if @course.update_attributes(course_params)
puts "students should now be added to course"
end
end
def course_params
params.require(:course).permit(:description, :status, course_students_attributes: [:id], course_jobs_attributes: [:id])
end
end我走的路对吗?
发布于 2016-01-15 02:21:01
如果您的关系是多对多的,则在关联声明中缺少关键字through:
class Course < ActiveRecord::Base
has_many :students, through: :course_students
accepts_nested_attributes_for :course_students
end
class Student < ActiveRecord::Base
has_many :courses, through: :course_students
endhttp://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
还要小心使用accepts_nested_attributes_for,特别是验证。你可以在这里阅读更多内容:https://robots.thoughtbot.com/accepts-nested-attributes-for-with-has-many-through
https://stackoverflow.com/questions/34796685
复制相似问题