문제

I'm trying to set a variable in my before_filter, but always get the error "undefined local variable or method 'question' for 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

Thank you very much!

도움이 되었습니까?

해결책

You need to make it an instance variable using the @ symbol. Also, you may want to consider moving this into a private method (see below) since this most likely is not a public action.

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top