Before_filter没有调用方法,设置局部变量

时间:2013-10-03 14:44:48

标签: ruby-on-rails before-filter

我正在尝试在我的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

非常感谢!

1 个答案:

答案 0 :(得分: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