Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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中添加一行:

@H_359_16@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框架的意愿.

大佬总结

以上是大佬教程为你收集整理的ruby-on-rails – 如何RESTful更新has_and_belongs_to_many集合?全部内容,希望文章能够帮你解决ruby-on-rails – 如何RESTful更新has_and_belongs_to_many集合?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。