ruby-on-railsruby-on-rails-4actionmailerlink-tobutton-to

Rails: Is it possible to Trigger a mailer method with a link_to or button_to method?


I'm trying to create an admin Tool where the admins can send emails that are already there with a button.

I have a class FamilyMailer < ActionMailer::Base with this method birthdaymailer

Is there a way for me to trigger this from the view ?

I have seen a lot of answers on StackOverFlow, but it doesn't really work.

The closest conclusion I have came across is that the Mailer gets triggered this way FamilyMailer.birthdaymailer in the view and create a return to main page.

I was wondering if there would be a better way.


Solution

  • Sure!

    Say you've got a mailer, called UserMailer.

    Set up your controller action:

    # my_controller.rb
    
    def send_mail
      @parameters = Model.get_parameters
      UserMailer.name_of_action(@parameters).deliver
    end
    

    Set up your route:

    get send_mail, to: 'my_controller#send_mail', as: :send_mail
    

    Then make your link!

    link_to 'Send mail', send_mail_path, class: "big-button"
    

    Voila.