Reputation: 387
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!
Upvotes: 0
Views: 637
Reputation: 7070
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
Upvotes: 6