catmal
catmal

Reputation: 1758

Rails mailer working on controller but not on model

I have set a mailer:

def created_poll_email(poll)
    @poll = poll
    mail(subject: 'A new poll was created! ' + @poll.question)
  end

Firstly I was calling it on polls controller:

  def create
   @poll = Poll.new(poll_params.merge(user: current_user))
   if @poll.save
   PollMailer.created_poll_email(@poll).deliver_now

And it was working fine.

Now I want to move it to a callback on model:

after_save :send_email

def send_email
  PollMailer.created_poll_email(@poll).deliver_now
end

But now i get error undefined method `question' for nil:NilClass. I tried to set also other callbacks as after_create or after_commit but same result. Why is this happening and how can I fix?

Upvotes: 3

Views: 42

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51151

You should replace @poll, which isn't set inside your model, with self:

def send_email
  PollMailer.created_poll_email(self).deliver_now
end

Upvotes: 3

Related Questions