0

我正在尝试在我的 before_filter 中设置一个变量,但总是收到错误“未定义的局部变量或 AnswersController 的方法'问题'”:

    class AnswersController < ApplicationController
        before_filter :get_question

        def create
            @answer = question.answers.new(params[:answer])
            @answer.user = current_user
            @answer.save
            flash[:notice] = 'Answer posted successfully.'
            redirect_to request.referer
        end

            def get_question
                question = Question.find(params[:question_id])
            end
    end

非常感谢!

4

1 回答 1

6

@您需要使用该符号使其成为实例变量。此外,您可能需要考虑将其移至私有方法(见下文),因为这很可能不是公共操作。

class AnswersController < ApplicationController
    before_filter :get_question

    def create
        @answer = @question.answers.new(params[:answer])
        @answer.user = current_user
        @answer.save
        flash[:notice] = 'Answer posted successfully.'
        redirect_to request.referer
    end

    private

    def get_question
        @question = Question.find(params[:question_id])
    end
end
于 2013-10-03T14:50:29.277 回答