首页 > 解决方案 > Rails 中的错误 SENDING POST 和 HTTPPARTY 语义错误我的请求

问题描述

这是我启动方法时的错误 {"errors"=>{"users"=>["Missing data for required field."]}, "msg"=>"请求格式正确但无法由于语义错误而紧随其后。"}

class BookingNotifier
include HTTParty
def initialize(booking_id)
  @booking = Booking.find booking_id
  @venue = @booking.event.service.venue
  @body = { "users" => [] }
  @headers = {
      "Accept" => "application/json",
      "Authorization" => "ENV_KEY",
      "Content-Type" => "application/json"
  }
end

def send_venue_notification
  venues_objects = []
    if @venue.notifications_enabled
      venues_objects << { "cellphone" => @booking.event.service.venue.phone,
                          "country_code" => "+57",
                          "user_session_keys" => [{ "key" => "Nombre",   "value" => @booking.profile.name },
                                                  { "key" => "Centro",   "value" => @booking.event.service.venue.name },
                                                  { "key" => "Cupos",    "value" =>  @booking.quantity },
                                                  { "key" => "Horarios", "value" => @booking.time.strftime("%I:%M %p el %d/%m/%Y") }] }.to_json
      @body["users"] = venues_objects
      make_request_venue
    end
end

def make_request_venue
  HTTParty.post("http://api.treble.ai/api/poll/49/deploy", headers: @header, body: @body)
end

标签: ruby-on-railsjsonrubyhash

解决方案


to_json问题是在错误的地方调用引起的。

整个请求正文应作为 JSON 发送。在您的代码中,您需要to_json一个哈希值,该哈希值稍后会被推送到@body["users"]数组中。

to_json请在发送请求时删除send_venue_notification并调用它:@body

HTTParty.post("http://api.treble.ai/api/poll/49/deploy", headers: @headers, body: @body.to_json)

推荐阅读