在 rails 的输入字段中使用 nexmo gem 发送短信

Send SMS using nexmo gem from input field in rails

我正在尝试向使用 Nexmo 在输入字段中输入的号码发送短信 gem

这是我目前的方法,但似乎不起作用

pages/test.html.erb

<%= form_tag "/pages/send_sms" do -%>
  <%= text_field_tag "number" %>
  <%= submit_tag "Send" %>
<% end -%>

routes.rb

Rails.application.routes.draw do
  get 'pages/home'
  post '/pages/send_sms', as: 'send_sms'
  get 'test', to: 'pages#test'
  root 'pages#home'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

pages_controller.rb

def send_sms
    @number = params[:number]
    nexmo = Nexmo::Client.new(
    key: ENV['NEXMO_API_KEY'],
    secret: ENV['NEXMO_API_SECRET']
    )
    notification = "Download the app through this link"


    response = nexmo.send_message(
      from: "GLAM360",
      to: params['number'],
      text: notification
    )
    if response['messages'].first['status'] == '0'
      redirect_to root_path
    end

  end

这是我在终端看到的

Started POST "/pages/send_sms" for 127.0.0.1 at 2017-10-08 00:35:45 +0400
Processing by PagesController#send_sms as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"zPj5PcZrD+uNYxvvfDio8B5uNWitg0vMw+3Vm8KbvQumbNWzsgN4sBJDKsi2srx0rSatiOISegWHQFE860
JxcA==", "number"=>"+971585959698", "commit"=>"Send"}
No template found for PagesController#send_sms, rendering head :no_content
Completed 204 No Content in 803ms

任何帮助将不胜感激

错误本身会告诉您该怎么做。你没有什么选择。

  1. 首先针对您的情况,如果最后一次检查,只需添加另一个重定向 条件失败。在您的情况下,它失败了,因此要求使用默认模板。如果您指定一个 else 子句,您可以在其中 描述它应该去哪里(用警告消息再次对表单说),rails 会自己处理。

if response['messages'].first['status'] == '0' redirect_to root_path else redirect_to test_path end

  1. 我使用了你的脚本并添加了一个 send_sms.html.erb 状态 根据响应从控制器传递的变量 nexmo.send_message 函数。喜欢 "Success" 或失败和 一切正常,在网页上它会通知我状态,我也收到了一条短信。这是我更喜欢更好的用户体验。
  2. 如果我必须这样做,我会对脚本做很多更改。建议永远不要依赖外部 API,始终将您对外部 API 所做的交互包装在界面中。我将包装 Nextio 脚本,将其从控制器中取出并将它们放在一个界面中(在 lib 中有一个 class 或在 helper 中有一个包装函数,并使用界面与之交互)并将通过以下方式与它交互我的控制器。尽量不要将逻辑放在控制器中。我还将使用 begin rescue 块与外部 API 进行交互,并将阅读所有错误并考虑如何处理它们。最后,对于流程,我会为用户提供更多信息,而不是让他们悬而未决。我会将他们重定向到另一个页面,如 send_sms 并为他们提供状态或使用警报消息告诉他们状态是什么。
  3. 最后,我会为这些作业使用后台任务(这可能需要一些时间,具体取决于外部服务器)。使用类似 sidekiq 的东西。