Ask A Question

Notifications

You’re not receiving notifications from this thread.

Setup noticed to send emails through a mailer?

Mark asked in Gems / Libraries

Hi Chris,

Sorry, I didn't "notice" (a lot to unpack here about my notice abilities) that you had a dedicated section for questions:

I was wondering how you configure your Noticed gem to work with mailers.

I had setup my post_controller to use the NewPostNotification.with(post: @post).deliver_later(Audience.all), where Audience is the model instead of the User model.

From my Posts controller

```ruby
def create
    @post = current_user.posts.build(post_params)

    respond_to do |format|
      if @post.save
        NewPostNotification.with(post: @post).deliver_later(Audience.all)
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end
 ````

From my mailer

```ruby
def new_post_notification
  @post = params[:post]
  mail(to: @post.recipient, subject: "My subject")
end
```

From my NewPostNotification class

class NewPostNotification < Noticed::Base
  # Add your delivery methods
  #
  # deliver_by :database
  deliver_by :email, mailer: "AudienceMailer"
  # deliver_by :slack
  # deliver_by :custom, class: "MyDeliveryMethod"

  # Add required params
  param :post

  # Define helper methods to make rendering easier.
  #
  def message
    t(".message")
  end

  def url
    post_path(params[:post])
  end
end

I'm currently getting an error: NoMethodError: undefined method `recipient' for nil:NilClass . This makes me think that, well there's not recipient method on my @post, but that ultimately I'm not passing the information from the notification to my mailer method correctly, but I'm struggling to figure that out at the moment.

Thank you.

Best,
Mark

Reply

In your mailer you have:

mail(to: @post.recipient, subject: "My subject")

That should be

  mail(to: params[:recipient], subject: "My subject")

👍

Reply

:) Thank you Chris!

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.