NoMethodError in ChatRoomMessagesController - ruby-on-rails

I am doing an AJAX call as the following and trying to parse the JSON recieved in Rails as bellow
AJAX
local_data = {chat:{room_name: chatRoomName ,message: message}}
$.ajax({
type: "POST",
url: '/chat_notify',
dataType: 'json',
async : false,
data: local_data,
success: function(data) {
alert("working");
}
});
Ruby
def notify
#data = ActiveSupport::JSON.decode(params)
#chat_room = ChatRoom.where(:slug => data.chat.name)
#puts #chat_room
puts params.chat
RestClient.post 'https://api.pushbots.com/push/all',
{ "platform" => [0,1] ,
"msg" => "Harsha sent a message." ,
"sound" => "pulse",
"alias" => "harsha#mink7.com",
"badge" => "1",
"payload" => { "type" => "Chat", "chat_id" => 1 } }.to_json,
headers = { "x-pushbots-appid" => APP_CONFIG['PUSHBOTS_APPID'],
"x-pushbots-secret" => APP_CONFIG['PUSHBOTS_SECRET'],
:content_type => :json }
render json: true
end
Error

You need to paste your error trace
But I think the problem might in below
puts params.chat
there is no chat method for params , just remove it
or
…………"payload" => { "type" => "Chat", "chat_id" => 1 } }.to_json
you need require 'json' to make .to_json available

Related

how to stub a post request with the required response in rails minitest

I am trying to stub a post request with the below response
{ 'data' => {
'detections' =>
[
[{
'language' => 'en',
'isReliable' => false,
'confidence' => 0.134
}],
[{
'language' => 'ar',
'isReliable' => false,
'confidence' => 0.9882
}]
]
} }
Can anyone help
You can use webmock https://github.com/bblimke/webmock#stubbing-requests-based-on-method-uri-body-and-headers
response = { 'data' => {'detections' =>[[{'language' => 'en','isReliable'=>false,'confidence' => 0.134}],[{'language' => 'ar','isReliable' => false,'confidence' => 0.9882 }]]}}
stub_request(:post, "url").with(<if needed>).to_return(status: 201, body: response.to_json, headers: { 'Content-Type' => 'application/json'})

Error SENDING POST in rails and HTTPPARTY semantic error my request

this is my error when I lanunched my method {"errors"=>{"users"=>["Missing data for required field."]}, "msg"=>"The request was well-formed but was unable to be followed due to semantic errors."}
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
The problem is caused by to_json called in the wrong place.
The whole request body should be sent as a JSON. In your code, you call to_json for a hash that is later pushed into #body["users"] array.
Please remove to_json from send_venue_notification and call it for the #body when sending the request:
HTTParty.post("http://api.treble.ai/api/poll/49/deploy", headers: #headers, body: #body.to_json)

Rest client post request, error with multipart

I have the following ajax request which works fine, but when i try the same through rest-client ruby gem i'm getting the following error
"{\"error\":{\"message\":\"Wrong request body. Check if all parameters set correctly\",\"code\":401},\"cartItems\":[]}"
JS:
dataContentType = 'application/json'
data = new FormData
if dataContentType == 'text/xml'
data.append 'data', new Blob([ $('#requestXml').val() ], type: 'text/xml')
else
data.append 'data', new Blob([ $('#requestJson').val() ], type: 'application/json')
console.log('requestJson', $('#requestJson').val())
fileIdx = 0
$('input[type=file]').each (i, value) ->
`var i`
i = 0
while i < value.files.length
data.append 'file[' + fileIdx + ']', new Blob([ value.files[i] ], type: 'application/octet-stream'), value.files[i].name
fileIdx++
i++
return
$.ajax
type: 'POST'
url: 'https://imatsandbox.materialise.net/web-api/cartitems/register'
data: data
cache: false
contentType: false
processData: false
beforeSend: (request) ->
request.setRequestHeader 'Accept', dataContentType
return
dataType: 'text'
success: (data, textStatus, jqXHR) ->
data variable contains this
{"currency":"USD","cartItems":[{"toolID":"toolID","MyCartItemReference":"some reference","modelID":"modelID","modelFileName":"","fileUnits":"mm","fileScaleFactor":"1","materialID":"00e005a8-b29b-4196-ba4e-57ac1c4ce60c","finishID":"bba2bebb-8895-4049-aeb0-ab651cee2597","quantity":"1","xDimMm":81.266,"yDimMm":159.935,"zDimMm":10.096,"volumeCm3":15.5864,"surfaceCm2":260.288,"iMatAPIPrice":"25.0","mySalesPrice":"26.0"}]}
I tried with the following using rest client
request = RestClient.post("https://imatsandbox.materialise.net/web-api/cartitems/register",{:currency => "USD",:cartItems => [{:toolID => "toolID",:MyCartItemReference => "some reference",:modelID => "modelID",:modelFileName => "",:fileUnits => "mm",:fileScaleFactor => "1",:materialID => "00e005a8-b29b-4196-ba4e-57ac1c4ce60c",:finishID => "bba2bebb-8895-4049-aeb0-ab651cee2597",:quantity => "1",:xDimMm => "81.266",:yDimMm => "159.935",:zDimMm => "10.096",:volumeCm3 => "15.5864",:surfaceCm2 => "260.288",:iMatAPIPrice => "25.0",:mySalesPrice => "26.0"}], :multipart => true})
In coffee script it works fine, when i try in the rest client it throws mentioned error.
EDIT:

Making POST Request to GCM server for notification key fails from Rails Controller

I have try to making a POST request to google cloud messaging server as follow from my Rails controller using httparty gem
#response = HTTParty.post("https://android.googleapis.com/gcm/notification",
:body => {
:text => '{
"operation" : "remove",
"notification_key_name": "43",
"registration_ids": [
"dmfbvTrqeSo:APA91bFmk_zTryZi-2-BrjZK-zxN3nmQxl8tIUJriTl7EwRZsnHq3UAMNQ2O_mxLVes7WLHnW6INx21UdKwm64ReUpd5bKTE0uinrPau2WVrAUkfUyRKxlIGLD2xLKbNiSGjAeNIDAhe"
]
}'.to_json
},
:headers => {
'Content-Type' => 'application/json',
'Authorization' => 'key=AIzaSyDQiBiYk433JhWKWFZZGAU3c08tWjCzU5o',
'project_id' => '857642310184'
}
)
#json = JSON.parse(#response.body)
render :json => #json
The response I got it not a notification key. It is
{
"error": "BadJsonFormat"
}
What's wrong in my code?
My Rails controller request format is
POST /api/fcm HTTP/1.1
Host: localhost:3000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: cfd40d1e-81f4-5402-a3cd-f6749f868291
{
"user_id" : "42"
}
I guess httparty gem expects json data
So replace
:body => {
:text => '{
"operation" : "remove",
"notification_key_name": "43",
"registration_ids": [
"dmfbvTrqeSo:APA91bFmk_zTryZi-2-BrjZK-zxN3nmQxl8tIUJriTl7EwRZsnHq3UAMNQ2O_mxLVes7WLHnW6INx21UdKwm64ReUpd5bKTE0uinrPau2WVrAUkfUyRKxlIGLD2xLKbNiSGjAeNIDAhe"
]
}'.to_json
},
:headers => {
'Content-Type' => 'application/json',
'Authorization' => 'key=AIzaSyDQiBiYk433JhWKWFZZGAU3c08tWjCzU5o',
'project_id' => '857642310184'
}
with
:body => {
:text => {
:operation => "remove",
:notification_key_name => "43",
:registration_ids => [
"dmfbvTrqeSo:APA91bFmk_zTryZi-2-BrjZK-zxN3nmQxl8tIUJriTl7EwRZsnHq3UAMNQ2O_mxLVes7WLHnW6INx21UdKwm64ReUpd5bKTE0uinrPau2WVrAUkfUyRKxlIGLD2xLKbNiSGjAeNIDAhe"
]
}
}.to_json,
:headers => {
'Content-Type' => 'application/json',
'Authorization' => 'key=AIzaSyDQiBiYk433JhWKWFZZGAU3c08tWjCzU5o',
'project_id' => '857642310184'
}
Try removing to to_json on post. This would work if you were calling it for a Hash, but what it's doing here is double-escaping your string (which is already valid JSON).
If you want to send a minimal JSON request (i.e. without the extra spaces and carriage returns), you can also use
JSON.parse('{
"operation" : "remove",
...
}').to_json

Change in value of JSON data at receiver end

I am sending post request to facebook graph api using Httparty gem.
My code is
message_data ={
"recipient" => {
"id" => recipient_id
},
"message" => {
"attachment" => {
"type" => "template",
"payload" => {
"template_type" => "generic",
"elements" => [
{
"title" => "Titilize",
"subtitle" => "Subtitle"
}
]
}
}
}
}
options ={
"query": {access_token: #page_access_token},
"body": message_data
}
HTTParty.post("https://graph.facebook.com/v2.6/me/messages",options)
Httparty will send data by converting hash into json.
Problem is at the end point data is receiving differently not as i expected (maybe httparty is not parsing properly).
Someone help me with this.
Thanks
Seems like you have to set the Content-Type header. There may be issues with the Hash syntax depending on your version of Ruby, so check out this open ticket: https://github.com/jnunemaker/httparty/issues/472
str = "{\"recipient\":{\"id\":\"1291831200828847\"},\"message\":{\"attachment\":{\"typ‌​e\":\"template\",\"payload\":{\"template_type\":\"generic\",\"elements\":[{\"titl‌​e\":\"Titilize\",\"subtitle\":\"Subtitle\"}]}}}}"
options {
:headers => {"Content-Type" => "application/json"},
:query => {access_token: #page_access_token},
:body => str
}
HTTParty.post("https://graph.facebook.com/v2.6/me/messages", options)

Resources