更新nested_attributes

时间:2016-01-14 18:06:47

标签: ruby-on-rails json

课程has_many学生和学生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

我是在正确的道路上吗?

1 个答案:

答案 0 :(得分:0)

如果您的关系是多对多,那么您在关联声明中缺少关键字:

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
end

http://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