수정해야 할 리소스를 올바르게 식별해야합니다. 이 경우 수정하려는 리소스는 클래스와 학생 간의 관계입니다.이를 Enrollment
이라고합니다.
has_many :through
을 우선적으로 사용하는 것은 레일에서 통상적으로 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, :course_id => @course.id), :method => :delete %>
:enrollment_id
가야와 구문 vineg의 작은 비트가 자리 표시 자 역할을 위 라인에
1
ar은 Rails 프레임웍의 의지를 좌지우지하고 있음을 상기시켜줍니다.
덕분에, 그것은 두 가지 사소한 변경으로 매우 잘 작동했습니다 : 1. @ student.courses.destroy (params [: course_id])를 호출하면 당연히 찾고 있었기 때문에 ActiveRecord :: AssociationTypeMismatch를 받았습니다. 우선 올바른 코스 (@ student.courses.find (params [: course_id]))를 찾은 다음이를 제거하여이 문제를 해결했습니다. 2. 코스를 파괴하고 싶지 않고 연관성을 삭제하기 때문에 파괴 대신 삭제 호출을 사용했습니다. –
효과가 좋았습니다. 변경 사항을 반영하기 위해 예제를 업데이트했습니다. – austinfromboston