使用Rails和Twilio发送短信消息

5

我是新手,对于Ruby和Ruby on Rails还不熟悉,现在想设置Twilio发送短信。

到目前为止,在我的Rails应用程序中有以下代码:当我尝试发送短信时,出现以下错误:

Missing template twilio/send_text_message, application/send_text_message with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :slim, :coffee, :haml]}.

我的初始化程序

#config/initializers/twilio.rb (removed keys)
require 'twilio-ruby'

  account_sid = "XXXXXXXXX"
  auth_token = "XXXXXXX"
  $twilio_phone_number = "+XXXXXXXXXX"

  $twilio_client = Twilio::REST::Client.new account_sid, auth_token

然后在路由中添加。
#routes.rb

post 'twilio/send_text_message' => 'twilio#send_text_message'

然后我有我的Twilio控制器

#twilioController
class TwilioController < ApplicationController

  def index
  end

  def send_text_message
  end
end

在我看来,我已经设置了一个表单让用户输入一条消息并将其发送到我的手机(因为我处于试用模式并且已验证)。

#ShareWithWorld.html.slim

= form_for :twilio, url: '/twilio/send_text', method: :post do |f|
  =f.text_field "Hey"
  =f.submit "Send Text"
1个回答

4
你收到该错误的原因是因为你没有要渲染的视图,例如app/views/twilio/send_text_message.html.slim
如果代码在不中断的情况下执行完操作,它将尝试呈现相关的视图。
class TwilioController < ApplicationController
  def send_text_message
    $twilio_client.account.messages.create(
      :from => '+14159341234',
      :to => '+16105557069',
      :body => ..params from form..
    )

    redirect_to root_path, notice: 'Your SMS has been sent' # This is the interrupt that will make it so it doesn't try to render the view
  end
end

你写的代码产生了无限循环。在我关闭开发服务器之前,它发送了+20条相同的文本消息。罪魁祸首是重定向。在我的情况下,它似乎导致了触发控制器操作的表单重新提交。 - Nick
@Nick,如果你重定向到发送文本的操作,可能会产生无限循环。我可能不应该假设root_path不是发送文本消息的操作。 - Brandon Cordell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接