无法找到带有' =

时间:2016-04-04 21:10:16

标签: ruby-on-rails

我有一个嵌套资源,我试图用嵌套资源创建一个表单。新页面有效,但是当我尝试访问该节目时,我会在标题上看到错误。这是我的代码:

的routes.rb

resources :courses do
  resources :lessons, shallow:true
end

lessons_controller.rb

class LessonsController < ApplicationController
  before_action :set_lesson, only: [:show, :edit, :update, :destroy]
  before_filter(:get_course)

  # GET /lessons
  # GET /lessons.json
  def index
    @lessons = Lesson.all
  end

  # GET /lessons/1
  # GET /lessons/1.json
  def show
  end

  # GET /lessons/new
  def new
    @lesson = Lesson.new
  end

  # GET /lessons/1/edit
  def edit
  end

  # POST /lessons
  # POST /lessons.json
  def create
    @course = Course.find(params[:course_id])
  @lesson = Lesson.new(:course=>@course)



    respond_to do |format|
      if @lesson.save
        format.html { redirect_to @lesson, notice: 'Lesson was successfully created.' }
        format.json { render :show, status: :created, location: @lesson }
      else
        format.html { render :new }
        format.json { render json: @lesson.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /lessons/1
  # PATCH/PUT /lessons/1.json
  def update
    respond_to do |format|
      if @lesson.update(lesson_params)
        format.html { redirect_to @lesson, notice: 'Lesson was successfully updated.' }
        format.json { render :show, status: :ok, location: @lesson }
      else
        format.html { render :edit }
        format.json { render json: @lesson.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /lessons/1
  # DELETE /lessons/1.json
  def destroy
    @lesson.destroy
    respond_to do |format|
      format.html { redirect_to lessons_url, notice: 'Lesson was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_lesson
      @lesson = Lesson.find(params[:id])
    end

def get_course
    @course = Course.find(params[:course_id])
end

    # Never trust parameters from the scary internet, only allow the white list through.
    def lesson_params
      params.require(:lesson).permit(:code, :course_id)
    end
end

如果我需要添加任何其他内容,请告诉我。谢谢!

1 个答案:

答案 0 :(得分:2)

  

当我尝试访问节目时

据推测,由于您已在routes.rb中定义了shallow: true,因此您正在向/lessons/1之类的请求发出请求。请注意过滤器的顺序:

 before_action :set_lesson, only: [:show, :edit, :update, :destroy]
 before_filter(:get_course)

过滤器按照定义的顺序运行。在这种情况下,set_lesson过滤器会在get_course过滤器之前运行。执行get_course过滤器时,它将尝试在params散列中查找course_id。在&#34;浅&#34;路由,该参数不存在,因此params[:course_id]将为nil。因此

Course.find(params[:course_id])

提出异常。

对于&#34;浅&#34; route,嵌套资源的ID(课程)就是所需要的。更改课程过滤器以排除show动作:

before_filter :get_course, except: :show

或者不要使用浅路线。

此外,before_action优先于before_filter

相关问题