大佬教程收集整理的这篇文章主要介绍了ruby-on-rails – 如何RESTful更新has_and_belongs_to_many集合?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
最好的方法是什么?
在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,请注明来意。