【问题标题】:how to use Twilio SMS params[:Body] to search a rails database如何使用 Twilio SMS params[:Body] 搜索 rails 数据库
【发布时间】:2015-08-10 23:51:16
【问题描述】:

您好,我正在尝试搜索我的数据库以使用 twilio 从短信正文中查找食谱。到目前为止,这是我在控制器中的代码

 def process_sms
    @recipe = Recipe.find_by(params[:title])
    render 'process_sms.xml.erb', :content_type => 'text/xml'
  end

还有我的路线:

root          'recipes#index'
  devise_for    :users
  resources     :recipes
  post          'twilio/voice' => 'twilio#voice'
  post          'twiliosms/send_sms' => 'twiliosms#send_sms'
  match         'twiliosms/process_sms' => 'twiliosms#process_sms', via: :all

我希望能够从 SMS 中搜索食谱标题并呈现一些 xml。当前的实现一遍又一遍地发回相同的配方。我认为这与未在同一控制器操作中传递 twilio params[:Body] 并使用它来匹配 recipe(params[:title]) 但不完全确定有关。任何帮助,将不胜感激。谢谢!

【问题讨论】:

    标签: ruby-on-rails sms twilio


    【解决方案1】:

    这里是 Twilio 开发者宣传员。

    您提到了params[:Body],它是SMS 消息文本的参数,但是您使用params[:title] 进行搜索。在来自 Twilio 的传入 webhook 的上下文中,params[:title] 将为 nil,所以我猜您返回的配方没有标题。

    我认为你应该使用:

    def process_sms
      @recipe = Recipe.find_by(title: params[:Body])
      render 'process_sms.xml.erb', :content_type => 'text/xml'
    end
    

    让我知道这是否有帮助。

    [编辑] 更新了对find_by的调用

    【讨论】:

    • 嗨@philnash 我收到以下内部服务器错误。让我知道你的想法。谢谢!'Recipe Load (0.9ms) SELECT "recipes".* FROM "recipes" WHERE (Tacos) LIMIT 1 SQLite3::SQLException: no such column: Tacos: SELECT "recipes".* FROM "recipes" WHERE (Tacos) LIMIT 1 Completed 500 Internal Server Error in 3ms (ActiveRecord: 0.9ms) ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column: Tacos: SELECT "recipes".* FROM "recipes" WHERE (Tacos) LIMIT 1): app /controllers/twiliosms_controller.rb:26:in `process_sms''
    • 'SQLite3::SQLException: no such column: Tacos: SELECT "recipes".* FROM "recipes" WHERE (Tacos) LIMIT 1 Completed 500 Internal Server Error in 38ms (ActiveRecord: 0.9ms)'我相信它基本上是在告诉我架构中没有 Body 列。
    • 啊,我的错,find_by 方法不只是接受一个字符串。在我对Recipe.find_by(title: params[:Body]) 的回答中更新了它。试试看。
    • 假设您的模型有一个 title 字段,我从您的上下文中猜测。
    • 很高兴听到这个消息!很想知道您正在构建什么,请随时通过 philnash@twilio.com 给我发送电子邮件!
    【解决方案2】:

    您可以考虑在控制器函数中使用.where(假设您的模型列名为“title”):

    def process_sms
      @recipe = Recipe.where(title:params[:title])
      render 'process_sms.xml.erb', :content_type => 'text/xml'
    end
    

    【讨论】:

    • 嘿,Fabio,感谢您的回复以及如何渲染实际数据的想法?
    • 您介意在您的问题中添加有关调用“process_sms”操作的 Rails 日志吗?这可能会显示另一个线索。
    猜你喜欢
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    相关资源
    最近更新 更多