微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – 如何RESTful更新has_and_belongs_to_many集合?

我有两个脚手架生成的模型,学生和班级.它们与has_and_belongs_to_many实现了多对多关系.
我希望能够改变学生所在的课程以及每个班级的学生.也就是说,我想修改学生的类变量(从中添加删除项目),反之亦然.
我如何RESTful地执行此操作?
如果我从学生的班级列表中删除一个班级,那么我似乎想在我的students_controller上调用更新.如果是这种情况,那么我应该作为参数传入什么来修改classes变量?另一个类集合(删除了适当的类)?
我的另一个想法就是在students_controller中调用一些动作(比如remove_class)并传入要删除的类的ID.这似乎很敏感,但不是RESTful.

最好的方法是什么?

解决方法

解决此问题的关键是正确识别要修改的资源.在这种情况下,您正在修改的资源是类和学生之间的关系,我将其称为注册.

在Rails中习惯使用has_many:优先使用has_and_belongs_to_many.您可能希望更改域逻辑以适应自定义,但如果您确实不需要存储关于关系的元数据,您也可以逆转趋势.

REST的一个关键思想是RESTful资源不需要映射到模型.您应该创建一个EnrollmentsController并在config / routes.rb中添加一行:

map.resources :enrollments

然后您可以创建和删除您的关系,如下所示:

class EnrollmentsController < ApplicationController
    def create
       @student = Student.find(params[:student_id])
       @course = Course.find(params[:course_id])
       @student.courses << @course
       if @student.save
         #do happy path stuff
       else
         #show errors
       end
    end

    def destroy
       @student = Student.find(params[:student_id])
       @course = @student.courses.find(params[:course_id])
       @student.courses.delete( @course )
    end
end

你可以为这些动作制作按钮:

<%= button_to "Enroll",enrollments_path(:student_id => current_student.id,:course_id => @course.id ),:method => :post %>
<%= button_to "Withdraw",enrollment_path(1,:student_id => current_student.id,:method => :delete %>

上面第1行充当占位符,其中:enrollment_id应该去,并且是一小段语法醋,以提醒你,你正在反对Rails框架的意愿.

原文地址:https://www.jb51.cc/ruby/265349.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐