嵌套资源控制器的问题

时间:2014-04-15 14:42:54

标签: ruby-on-rails resources nested controllers

过去两天我一直在使用嵌套资源,但我无法弄清楚与嵌套资源及其相应控制器相关的这个特定问题。创建嵌套资源时,创建相应的控制器是否通用?在这方面处理控制器的最佳做法是什么?任何提示和见解将不胜感激!

我的例子:

course.rb

class Course < ActiveRecord::Base
  has_many :course_students
  has_many :students, through: :course_students
end

student.rb

class Student < ActiveRecord::Base
  has_many :course_students
  has_many :courses, through: :course_students
end

course_student.rb

class CourseStudent < ActiveRecord::Base
  belongs_to :course
  belongs_to :student
end

的routes.rb

resources :courses do
  resources :students, controller: :courses_students
end

courses_students_controller.rb

class CoursesStudentsController < ApplicationController
  before_action :set_course_student, only: [:show, :edit, :update, :destroy]

  def index
   @course = Course.find(params[:course_id])
   @students = Student.all
  end

  def show
  end

  def new
   @course = Course.find(params[:course_id])
   @student = Student.new
  end

  def create
   @course = Course.find(params[:course_id])
   @student = Student.new(student_params)
   if @student.save
    @course.students << @student
    flash[:notice] = "Student form successfully submitted."
    redirect_to course_path(@course)
   else
    flash[:error] = "Unable to process your request."
    render :new
   end
  end

  def edit
  end

  def update
   Student.update(@student, student_params)
   redirect_to course_path(@course)
  end

  def destroy
   @student.destroy
   redirect_to course_path(@course)
  end

  private

  def set_course_student
   @student, @course = Student.find(params[:id]), Course.find(params[:course_id])
  end

  def student_params
  end
end

1 个答案:

答案 0 :(得分:0)

当您使用单独的模型时,您应该使用courses_students。

的routes.rb

resources :courses
resources :students
resources :courses_students

控制器

class CoursesStudentsController < ApplicationController

  def index
   @course_students = CourseStudent.all
  end

  def show
    @course_student = CourseStudent.find(params[:id])
  end

  def new
   @course_student = Student.new(course_student_params)
  end

  def create
    @course_student = Student.new(course_student_params)
     if @student.save
    redirect_to @course_student
   else
    render 'new'
   end
  end

  def edit
  end

  def update
     @course_student = CourseStudent.find(params[:id])
     if @course_student.update(course_student_params)
       redirect_to @course_student
     else
    redirect_to @course_student
  end

  def destroy
    @course_student = CourseStudent.find(params[:id])
    @course_student.destroy
    redirect_to courses_students_path
  end

  private

  def course_student_params
    params.require(:course_student).permit(:course_id, :student_id)
  end
end