Pass array of ids to custom get in Restangular - ruby-on-rails

I'm trying to pass an array of ids to my server using Restangular
var params = { profile_ids: _.map(fof, 'id') }
Restangular.all('mutual_friends').customGET('', params)
however, this results in the following query string being passed the my rails server
Started GET "/mutual_friends?profile_ids=231&profile_ids=2&profile_ids=254
how can I send the ids as an array? so the query string looks like:
/mutual_friends?profile_ids=[231, 2, 354]

Related

json data changed in the params

This is a webhook activity I am trying do using postman. The post content is the below json.
{
"model":{
"id":"560a32d2a1dcb7902a7ad596",
"name":"cool features",
"pos":32767.5
},
"action":{
"id":"567537b94332a7d8489a0d26",
"idMemberCreator":"55024f3fdd60428e915d2c2b",
"data":{
"board":{
"shortLink":"SUDki3AR",
"name":"recipe",
"id":"560a31fad96886a87cabf39a"
},
"list":{
"name":"cool features",
"id":"560a32d2a1dcb7902a7ad596"
},
"card":{
"shortLink":"sufSA867",
"idShort":18,
"name":"added",
"id":"567537b94332a7d8489a0d25"
}
},
"type":"createCard",
"date":"2015-12-19T10:55:53.904Z",
}
}
rails strips away the action key value from params. I can only get it using request.raw_post . But it is a string . Is there a way to get the action value in the json in params? String manipulation would be very difficult.
Rails sets the params controller and action on every request, so it overwrites your action.
As you already found out, you can get the request string and as you know it's json, you can parse it (by the way: your json is invalid, an extra , after date):
action = JSON.parse(request.raw_post)['action']

How to accept multiple URL parameters in Rails with the same key?

In Rails, when you want to send a list of values through a single array parameter, you usually do so by suffixing the URL parameter key with []. For example, the query string ?foo[]=1&foo[]=2&foo[]=3 is parsed as
params = { "foo" => [ 1, 2, 3 ] }
But for ?foo=1&foo=2&foo=3, only the last argument shows up in the params hash:
params = { "foo" => 3 }
Everything's fine while you can control the URL format; you can just use the [] syntax. But what if the URL is constructed by a remote system that you cannot influence, and that insists on the second format? How can one get the arguments unpacked properly?
Using the hint from #maxcal I came up with this solution (to avoid adding yet more gems to this completely bloated app that I'm working on):
current_query_string = URI(request.url).query
foo_values = URI::decode_www_form(current_query_string).
select { |pair| pair[0] == "foo" }.
collect { |pair| pair[1] }

Breeze.js Passthrough Predicate Odata Url

I am attempting to create an odata url with multiple breeze.js passthrough predicates using documentation from the folowing link: http://www.getbreezenow.com/documentation/query-using-json.
However the generated url looks nothing like an odata url eg:
var query = breeze.EntityQuery.from('User').using(this.manager).where("{ { 'userName': { '=': '123456' } } }");
var url = query._toUri(this.manager);
url is "User?$filter=%7B%20%7B%20'userName'%3A%20%7B%20'%3D'%3A%20'123456'%20%7D%20%7D%20%7D&$orderby=UserName" rather than "User?$filter=(UserName eq '123456')&$orderby=UserName".
I don't think you want a passthru query because this just passes your where clause thru intact without any processing. This is what happens when you quote the entire where clause.
If you want your query converted to 'odata' syntax then try the following:
var query = breeze.EntityQuery.from('Customers').using(em)
.where({ 'userName': { '==': '123456' } });
Note that the 'where' argument is NOT in quotes ( it is a standard javascript object), and the operator is '==', not '=';
or even simpler
var query = breeze.EntityQuery.from('Customers').using(em)
.where( { userName: '123456' });
Further info:
There are two forms of urls that can be generated from any breeze query. An OData form and a JSON form. If you want OData, (the default) then you either do nothing because it is the default or you can tell breeze explicitly with:
breeze.core.config.initializeAdapterInstance("uriBuilder", "odata");
If you want the json form, you would use
breeze.core.config.initializeAdapterInstance("uriBuilder", "json");
It also possible that you added a line to use the 'json' uriBuilder. Just omit this line if you want OData urls. You can still construct the query via the json syntax, but the URL will be output using OData syntax.
The Json form ( or uri) is useful for non OData servers.

How to access items in an api return string in Rails

I'm accessing the Google places API using HTTParty. Here's my code.
query = GOOGLE_API["search"].merge(:location => latlng.join(","))
response = HTTParty.get(GOOGLE_API["search"]["url"], :query => query)
#businessInfo = response
#business info contains a string of data from Google as expected, however, when I try to acccess the items using #businessInfo.index(0).item like I would with data from my database, I get nil.
This is a sample of what is contained in the variable -- {"html_attributions"=>[], "results"=>[{"geometry"=>{"location"=>{"lat"=>33.762835, "lng"=>-84.392724}}, "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/art_gallery-71.png", "id"=>"c551a5fdc78c273e6f498aa920733037199ebe01", "name"=>"World of Coca-Cola", "reference"=>"CnRoAAAAvpKSnn971Ur5ABYStk-EJfMvyFFFlBtd9LzwRT4H-PF50vS0CQtDCGkoW0QqKLHwFHV7Qmj32bgg-KjthkVENsBpGPxNAq_vcg4do-TQyi97y6mKxf3qUgoGxzGHePEAcqg15aATTl6Xdsq7Pl2b6hIQpzVIr4KO4ZDSx4tIqcH-ARoUPn-9yBSLi35lBM7gFm2KTPGREa0", "types"=>["art_gallery", "store", "establishment"], "vicinity"=>"Baker Street Northwest, Atlanta"}, {"geometry"=>{"location"=>{"lat"=>33.759925, "lng"=>-84.387158}}, "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png", "id"=>"32815dbf0963cb55dee871b96cc5100335f40400", "name"=>"Hard Rock Cafe Atlanta", "reference"=>"CnRtAAAApKIX3M3emqAzdsN3f0ntsi-M-
My question is, What syntax do I use to access the items and values so that I can work with them.
Thanks.
Your response object is an hash so you can access your response content in the following way:
puts response["results"]

form serialize problem

I have a form. I am trying to validate it through AJAX GET requests.
So i am trying to send the field values in the GET request data.
$('#uxMyForm').serialize();
the problem it is returning something undecipherable. I have used serialize before. This is totally bizzare.
the return value of serialize is
actionsign_upcontrollersitedataauthenticity_token=oRKIDOlPRqfnRehedcRRD7WXt6%2FQ0zLeQqwIahJZJfE%3D&customer%5BuxName%5D=&customer%5BuxEmail%5D=&customer%5BuxResidentialPhone%5D=&customer%5BuxMobilePhone%5D=&customer%5BuxDateOfBirth%5D=&customer%5BuxAddress%5D=&customer%5BuxResidentialStatus%5D=
i have no idea how to use this.
Thanks
update:
My question is how do i process such a request? like this?
puts params[:data][:customer][:uxName]
my GET request trigger looks like this
$.get('/site/sign_up',{data : $('#uxMyForm').serialize() }, function(data){
alert(data);
});
The above jquery lines generate the request.. on the action method i do the following
render :text => params
when i observe what is sent in the GET,in firebug PARAMS
**data** authenticity_token=oRKIDOlPRqfnRehedcRRD7WXt6%2FQ0zLeQqwIahJZJfE%3D&direct_customer%5BuxName%5D=&direct_customer%5BuxEmail%5D=&direct_customer%5BuxResidentialPhone%5D=&direct_customer%5BuxMobilePhone%5D=&direct_customer%5BuxDateOfBirth%5D=&direct_customer%5BuxAddress%5D=&direct_customer%5BuxResidentialStatus%5D=
the return value that i print in alert has
actionsign_upcontrollersitedataauthenticity_token=oRKIDOlPRqfnRehedcRRD7WXt6%2FQ0zLeQqwIahJZJfE%3D&direct_customer%5BuxName%5D=&direct_customer%5BuxEmail%5D=&direct_customer%5BuxResidentialPhone%5D=&direct_customer%5BuxMobilePhone%5D=&direct_customer%5BuxDateOfBirth%5D=&direct_customer%5BuxAddress%5D=&direct_customer%5BuxResidentialStatus%5D=
How does the form itself look. I have no experience with Ruby on rails - and if it builds the form in a new exciting way - but it looks as if there's only two form elements: authenticity_token and customer - where customer is an array of items. This is the data you posted, but I urldecoded it and put in some linebreaks:
authenticity_token=oRKIDOlPRqfnRehedcRRD7WXt6/Q0zLeQqwIahJZJfE=
&customer[uxName]=
&customer[uxEmail]=
&customer[uxResidentialPhone]=
&customer[uxMobilePhone]=
&customer[uxDateOfBirth]=
&customer[uxAddress]=
&customer[uxResidentialStatus]=
What you could do is to serialize the form to an array and clean it up before sending it using jQuery ajax request. I did something similar once when I had to serialize .net runat-server form elements:
var serializedData = $(form).serializeArray();
for( i=0; i < serializedData.length; i++)
{
// For each item in the array I get the input-field name after the last $ character
var name = serializedData[i].name;
var value = serializedData[i].value;
if( name.indexOf('$') != -1)
name = name.substr( name.lastIndexOf('$')+1 );
serializedData[i].name = name;
}
var ajaxPostData = $.param(serializedData);
So instad of blabla$ABCPlaceHolder$tbxEmail I got tbxEmail in the array. You could do the same to get uxName, uxEmail etc instead of the customer array.
Note then again, however, due to my inexperience with ruby that this may not be the best solution - maybe there's a setting you can change to build the HTML form differently?
Updated:
I'm not sure how ruby works, but after a googling I found you should be able to receive your values using params:customer as an array.
params:customer should contain an array of the values
{:uxName => "", :uxEmail => "" }
I hope that tells you something on how to receive the data. Maybe (warning - wild guess!) like this?
params[:customer][:uxName]

Resources