user2759575
user2759575

Reputation: 553

Undefined method when setting up mailers

I'm trying to get mailers set up in my application (for the first time) so that when a users question is answered they are notified via email.

My problem is I am unable to get the controller working without errors.

My routes look like this:

 resources :questions do
   resources :answers
 end

In my answers_controller I have this:

def create
  @answer = Answer.new(answer_params)
  @question = Question.find(params[:question_id])

if @answer.save
  UserMailer.question_answer(@user).deliver
 end 
end

In the user_mailer.rb file I have this:

 def question_answer(user) 
   @answer = Answer.new
   @question = @answer.question
   mail(:to => @question.user.email, :subject => "Your question was answered!")  
 end 

However, when posting an answer I get this error:

undefined method `user' for nil:NilClass

Upvotes: 0

Views: 38

Answers (1)

SSR
SSR

Reputation: 6438

You need to pass @answer in parameter like,

UserMailer.question_answer(@answer, @user).deliver

and you will get question from @answer. in mailer.rb

def question_answer(answer, user) 
  @answer = answer
  @question = @answer.question
  @user = user
  mail(:to => @question.user.email, :subject => "Your question was answered!")  
end

Now you will get each parameter to pass with email. in your question i figure out that you are passing only user and getting that user with question, but you will have a blank @question so user of that question will be blank. that's why you were getting nil class error.

Hope this help.

Upvotes: 2

Related Questions