I'm trying to make a simple contact us form so I need to implement the mailer.
I created a controller:
class ContactusController < ApplicationController
def index
@contact_us = Contactus.new
end
def new
redirect_to(action: 'index')
end
def create
@contact_us = Contactus.new(params[:contactus])
if @contact_us.deliver
flash[:notice] = "Thank-you, We will contact you shortly."
else
flash[:error] = "Oops!!! Something went wrong. Your mail was not sent."
end
render :index
end
end
As I don't want to save the data I used ActiveModel:
class Contactus
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
include ActionView::Helpers::TextHelper
attr_accessor :name, :email, :message
validate :name,
:presence => true
validates :email,
:format => { :with => /\b[A-Z0-9._%a-z\-]+@(?:[A-Z0-9a-z\-]+\.)+[A-Za-z]{2,4}\z/ }
validates :message,
:length => { :minimum => 10, :maximum => 1000 }
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def deliver
return false unless valid?
mail(
:to => "XXXXXXXX@gmail.com",
:from => %("#{name}" <#{email}>),
:reply_to => email,
:subject => "Website inquiry",
:body => message,
:html_body => simple_format(message)
)
true
end
def persisted?
false
end
end
Everything works fine. The routing is good, the validation works, but the only error I get is: undefined method mail for #<Contactus:0x007f9da67173e8>
I tried to make mailer with name Contactus and user Model code in that, but I got
the following error: private method new used
How can I use the ActionMailer function in ActiveModel?