简体   繁体   中英

Rails comparing zipcode based on user input against db and then mailing to employee

We have a Customer form that is not storing data but has a form that is then pushing the data to a contact. What I'd like to do is when the customer enters in their data is to take the zipcode from the form, compare it against all zipcodes and if it matches, send their contact information to the manager in their region.

In a nutshell Bill enters in 10001 and that matches the Zipcodes db which has a Region ID of 3. So the manager of Region 3 gets the email.

For the models I have:

Zipcode
belongs_to :region

Region
has_many :zipcodes, dependent: :destroy

Contact
include ActiveModel::Model
attr_accessor :first_name, :last_name, :company, :region, :email, :message_for_mailer, :inquiry, :address, :city, :state, :zipcode

In my ContactsController I have the following for the create:

 def create
  @contact = Contact.new(contact_params)
  @contact.valid?
  if captcha?
   ContactMailer.contact_request(@contact).deliver if @contact.valid?
  else
   @contact.errors.add(:base, 'Please verify you are human')
  end
  respond_with @contact
 end

My thought was the following:

def create
 @zipcode = Zipcode.all
 @contact = Contact.new(contact_params)
 @contact.valid?
 if captcha?
   if @contact.zipcode == @zipcode.zipcode
     ContactMailer.custom_request(@contact).deliver if @contact.valid?
   else
     ContactMailer.basic_request(@contact).deliver if @contact.valid?
   end
 else
   @contact.errors.add(:base, 'Please verify you are human')
 end
 respond_with @contact
end

But I'm pretty sure this won't work as I'm not actually comparing against the db. So how do I iterate over the Zipcode table with the results of the data that's being created?

I would use ActiveJob to create a job that can be performed after the response is sent. This makes the application more snappy as the user does not have wait for the email to be sent and frees up your web threads.

class ContactNotifierJob < ApplicationJob
  queue_as :default 
  def perform(contact)
    @zipcode = ZipCode.find_by(zipcode: contact.zipcode)
    @manager = @zipcode.try(:region).try(:manager)
    if @manager
      ContactMailer.notify_manager(@contact, @manager).deliver
    else
      ContactMailer.do_something_else(@contact).deliver
    end
  end
end

You can then simply spool up the job from your controller:

def create
  @contact = Contact.new(contact_params)
  @contact.errors.add(:base, 'Please verify you are human') unless captcha? 
  if @contact.save
    ContactNotifierJob.perform_later(@contact)
  end
  respond_with @contact
end

It will be performed as soon as the queuing system is free.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM