我收到多个用户的报告,即使他们只点击了按钮一次,也会收到多条短信验证消息。
以下代码处理该部分(控制器):
def sms
current_user.generate_sms_code!
current_user.sms
end
模特:
def generate_sms_code!
range = (10000..99999).to_a
update_attribute :sms_code, range[rand(range.length)]
end
def sms
TWILIO_CLIENT.account.sms.messages.create(
:from => TWILIO_SMS_NUMBER,
:to => self.phone,
:body => "Please confirm! Your verification code is: #{sms_code}"
)
end
也许自上次发送以来我需要在后端做些什么?任何想法如何解决这个问题或怎么做以防止向同一个用户发送多个短信?
详细信息:
我在前端贬值。
答案 0 :(得分:0)
天真的解决方案:
您可以向last_message_sent_at
模型添加User
属性,如果last_message_sent
小于1分钟(任意),则拒绝发送其他消息。
答案 1 :(得分:0)
我强烈建议您在数据库中记录所有SMS消息以供将来参考。这还可以让您查看某人是否已在最后X分钟内发送了特定消息或其他任何消息,从而阻止重复消息。当然,您仍然应该首先找出重复消息的发送原因,但这至少提供了一个安全网。
几年前,我做了一个发送短信的应用程序。这是我的Message类的模式,它表示发送的SMS消息:
create_table "messages", :force => true do |t|
t.text "body"
t.datetime "created_at"
t.integer "user_id"
t.string "to_number" #the phone number
t.datetime "sent_at"
t.boolean "successful"
t.text "kind" #a short string from a predefined list - "welcome", "daily_reminder", "task_complete" etc
end
您应该将所有SMS发送功能移到SMS类中,以便您的控制器代码可能如下所示:
@sms = @user.messages.create(:body => "Welcome to MyApp.com")
@sms.deliver
您可以通过几种不同的方式来阻止重复的邮件。一种方法是,如果最近发送了一条消息,则使消息无效,并确保.deliver方法不会发送未保存的消息(如果消息无效,则无法保存)。例如
class Message < ActiveRecord::Base
validate :not_a_repetition
def not_a_repetition
if Message.where(["user_id = ? and body = ? and id <> ? and sent_at > ?", self.user_id, self.body, self.id, 1.hour.ago]).any?
self.errors.add(:body, "has already been sent recently")
end
end
def deliver
return false if self.new_record?
#code for filling in any necessary fields (eg to_number) and sending the SMS here
...
end