首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更新nested_attributes

更新nested_attributes
EN

Stack Overflow用户
提问于 2016-01-15 02:06:47
回答 1查看 27关注 0票数 1

学生和学生has_many课程的课程

如何使用json API更新course以将多名学生分配到一门课程

模型

代码语言:javascript
复制
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

控制器

代码语言:javascript
复制
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

我走的路对吗?

EN

回答 1

Stack Overflow用户

发布于 2016-01-15 02:21:01

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

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34796685

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档