Rest client post request, error with multipart - ruby-on-rails

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:

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'})

Why am I getting ActionController::UnknownFormat when sending a file in a form?

about.html.erb
form_tag({ :action => 'contact_send'}, :format => :js, :multipart => true, :remote => true, :id => "mensaje") do
notifications.rb
class Notifications < ApplicationMailer
def contact_email(data)
#data = data
attachments["#{#data[:name].parameterize}.pdf"] = File.absolute_path(#data[:file].tempfile)
....
frontend_controller.rb
def contact_send
....
Notifications::contact_email(#parameters).deliver_now
respond_to do |format|
format.js
end
end
I have a contact_send.js.erb which it works when I don't add a file to the form, but get an error in respond_to do |format| when the file is sent.
Also the mail is sent with the file using letter_opener so there is no issue in there.
This is how I fixed the issue
$("form#mensaje").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/contact/send',
type: 'POST',
data: formData,
async: false,
success: function (data) {
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Remote true, does an AJAX request. And you can't do multipart while doing AJAX. At least now without a javascript (jQuery) upload plugin of sorts.

NoMethodError in ChatRoomMessagesController

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

Making a form on collection select - Rails

I am trying to create a form that submits on the collection select option, like when I select a value from the dropdown, it should post, what is posted below is not working,
<%= form_tag edit_zone_management_path, :method => 'get', :id => "bar" do %>
<%= collection_select :dropdown, :id, Server.where(:id => #arr),:id, :server_name, :prompt => true, :selected => #sid %>
<%end%>
Can someone please point out what is missing here?
Addition
There is some coffeescript that is bound to this collection select.
$ ->
$("#dropdown_id").live "change", -> // id of the collection_select
index = this.selectedIndex
uid = window.location.pathname.split("/")
if index == 0
index += 1
response = "{ \"key\": { \"value\" : #{index} } }"
#window.location.replace(uid[0]+ "/" + uid[1] + "/" + uid[2] + "/" + uid[3] + "/" +uid[4])
$.ajax({
type: 'POST',
url: '/configuration/zone_management/updategrid/',
data: response,
contentType: "application/json",
});
It looks like you are missing any handler for your $.ajax call, try adding some:
$.ajax({
type: 'POST'
url: '/configuration/zone_management/updategrid/'
data: response
contentType: "application/json"
success: (response) ->
console.log response
alert "Success fired"
error: (response) ->
console.log response
alert "Error fired"
})
This is just example, so adjust your handlers accordingly!
Good luck!

How do I turn this link_to_function to link_to in rails 3

I have this link_to_function
= link_to_remote 'Populate Info From ID', :url => {:controller => 'something',
:action => 'populate_from_id'},
:with => "'id=' + $('account_id').value + '&field_prefix=purchaser'",
:update => {:failure => 'account_id_error'}
I have converted many of them in a rails upgrade with , :remote => true, :method => :post
But i dont know how to add the with condition to grab the value out...any ideas
All the AJAX-specific options representing callbacks are gone in Rails 3 link_to helpers. You'll have to write your own javascript to handle more complex remote actions like your example.
Here's a quick rewrite:
# Your template
= link_to 'Populate Info From ID', :url => {:controller => 'something',
:action => 'populate_from_id'}, :id => "#populate_info"
# In javascript, assuming jquery and
# an element #account_id with a data-id attribute
$("#populate_info").on("click", function() {
$.ajax({
method: "POST",
data: { id: $('#account_id').data("id"), field_prefix: "purchaser" }
error: account_id_error
});
return false;
});
Useful blog post: http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/
Lots of great documentation here: http://api.jquery.com/jQuery.ajax/
You beat me to it I came up with this
$('.populate_id').click(function(e){
e.preventDefault();
var url = $(this).attr('href');
var failure = $('#' + $(this).attr('failure'));
failure.html('');
var element = $('#' + $(this).attr('element'));
var id = element.val();
var url_extra = 'account_id=' + id + '&field_prefix=purchaser';
$.ajax({
url: url,
data: url_extra,
type: 'post',
error: function (data) {
failure.html(data.responseText);
}
});
return false;
});

Resources