Shruthi R
Shruthi R

Reputation: 1923

Rails - Send Twilio messages for custom actions

In rails 4.2.4, I am using gem 'twilio-ruby' to send SMS. Right now I am calling this twilio method for particular action, eg: send otp message & it is working fine. But the issue is same message will send when I am calling other actions.

In development.rb

config.middleware.use Rack::TwilioWebhookAuthentication, Rails.application.secrets.twilio_auth_token, '/voice'

In user model,

def send_otp_notification
  begin
    client = Twilio::REST::Client.new Rails.application.secrets.twilio_account_sid, Rails.application.secrets.twilio_auth_token
    message = client.messages.create :from=> '+12015598867', :to=>"+#{self.mobile_number}", :body=> "Verify your otp: #{self.otp}"
  rescue Twilio::REST::RequestError => e
    puts "e = #{e}".red
  end
end

In mobile/api/user.rb,

user = User.new(params[:user])
user.save
user.send_otp_notification

Here, send_otp_notification method will call only once when user registers, right now when a user creates any other object(eg: create 'posts' table entry) then also otp message will send, how can I avoid this?

Upvotes: 1

Views: 233

Answers (3)

Raman
Raman

Reputation: 1281

You can modify your model to contain a boolean field that tells if a notification has already been sent for this user

class AddOtpSentToUsers < ActiveRecord::Migration
  def up
    add_column :users, :otp_sent, :boolean, default: false
  end

  def down
    remove_column :users, :otp_sent
  end
end 

And modify your function to be flexible in sending otp if it is requested to be sent again or for the first time

def send_otp_notification send_again = false
  if !self.otp_sent || send_again
    begin
      client = Twilio::REST::Client.new Rails.application.secrets.twilio_account_sid, Rails.application.secrets.twilio_auth_token
      message = client.messages.create :from=> '+12015598867', :to=>"+#{self.mobile_number}", :body=> "Verify your otp: #{self.otp}"
    rescue Twilio::REST::RequestError => e
      puts "e = #{e}".red
    end
  end
end

Upvotes: 1

bipin52165
bipin52165

Reputation: 168

ActiveRecord has two callback method after_save or after_create.You can use any one or both to call your function dynamically.You need to set those method in your model.No need to set condition or call at anywhere.

after_save :send_otp_notification

after_create :send_otp_notification

Upvotes: 1

Gupta
Gupta

Reputation: 10378

Using Active Record new_record

user = User.new(params[:user])
user.save
tmp = true
user.send_otp_notification if tmp.present?

Active Record Persistence new_record

hope this solve your issue!!!

Upvotes: 1

Related Questions