nulltek
nulltek

Reputation: 3337

Rails Conditional Mailer

I have a Rails app which tracks calls. Each time a new call is generated, I send an email to the staff that is assigned to aka the unit's medics (which is an association) via the medic_email field and I cc the new call to [email protected].

Currently what I have is working fine, but I would like to add a conditional in the mailer somehow to change the cc: address based off of a call's region (which is an association between call and region). So all calls in the Houston region are delivered to the medics assigned to the call and cc'd to [email protected] and all calls in the Dallas region are delivered to the medics assigned to the call and cc'd to [email protected]

What would be the correct way to setup a conditional in the mailer to do this based off of the current code I have written. Below are some excepts which might help explain the question better. If anything is unclear, please let me know and I will revise my question.

call_mailer-excerpt

  def new_call(medic, call)
    @call = call
    @medic = medic

    mail to: [@medic.medic_email], :cc => "[email protected]", subject: "New Call: #{@call.incident_number}"
  end

call.rb-excerpt

has_many :call_units
has_many :units, through: :call_units
belongs_to :region

  def send_mail(mail_type)
    units.each do |unit|
      CallMailer.send(mail_type, unit.incharge,  self).deliver
      CallMailer.send(mail_type, unit.attendant, self).deliver
    end
  end

region.rb-excerpt

attr_accessible :area
  has_many :calls

calls_controller.rb

  def create
    parse_times!
    @call = Call.new(params[:call])
    @call.dispatched_by = current_user.username

     if @call.save
      if @call.unit_ids.present?
        @call.send_mail(:new_call)
        send_new_sms
        redirect_to calls_path, notice: "Call #{@call.incident_number} was successfully created.".html_safe
      else
        redirect_to calls_path, notice: "Call #{@call.incident_number} was successfully created.".html_safe
      end
      else
        render :new
     end
  end

unit.rb

has_many :call_units
has_many :calls, through: :call_units
belongs_to :attendant, :foreign_key => :attendant_id, :class_name => 'Medic'
belongs_to :incharge, :foreign_key => :incharge_id, :class_name => 'Medic'

medic.rb-excerpt

has_many :units
has_many :units_attendant_name, :foreign_key => :attendant_id, :class_name => 'Unit'
has_many :units_incharge_name, :foreign_key => :incharge_id, :class_name => 'Unit'

Upvotes: 0

Views: 480

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

Simplest way would be to add a "copy_mail" column to the Region table.

rake db:migrate AddCopyMailToRegion copy_mail:string

Populate it with the right email addresses, then reference it in the mailer...

mail to: [@medic.medic_email], :cc => @call.region.copy_mail, subject: "New Call: #{@call.incident_number}"

Upvotes: 2

Related Questions