POST request in rails - ruby-on-rails

I need to create a post request in a somewhat weird(speaking leniently) format. The exact request to be sent should be in the following format
https://xyz.com/ping?app_id=
123&adv_id=345&event=sale&event_data="amt=30_USD;user_id=204050"
Its easy to send a post request to an url of the following format :-
https://xyz.com/ping?app_id=
123&adv_id=345&event=sale&amt=30_USD&user_id=204050
This can be achieved using code like this :-
Net::HTTP.post_form(URI.parse("http://xyz.com/ping"), params)
where, the params variable is appropriately populated(hash).
What modification should i make to account for this change from normal scenario, particularly to account for the double quotes around event data.

Read and adapt the information from the links below. After going through them, I can deduce 4 possible ways to do this:
Use Mechanize. See link 1
Do a post request from your controller using Net::HTTP. See link 2 - 3(3rd answer).
Post form data containing a hash or array. See links 4 - 7
Add hidden field to your form that will contain the extra data. See link 8
Use the params merge pattern ie Link 9
Using Ruby/Rails To Programmatically Post Form Data To Another Site
Submitting POST data from the controller in rails to another website
Post and redirect to external site from Rails controller?
http://rails.nuvvo.com/lesson/6371-action-controller-parameters
http://www.developer.com/lang/rubyrails/article.php/3804081/Techniques-to-Pass-and-Read-URL-Parameters-Using-Rails.htm
http://guides.rubyonrails.org/action_controller_overview.htm (the section 3.1 Hash and Array Parameters, then section 8 on Request Forgery Protection)
Rails: How do I make a form submit an array of records?
Ruby on Rails: Submitting an array in a form
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-hidden_field
Send querystring params as part of form post

You need to make sure that the event_data parameter is properly escaped to do this. I'm pretty sure that calling post_form will do this for you already.
params["app_id"] = 123
params["adv_id"] = 345
params["event"] = 'sale'
params["event_data"] = '"amt=30_USD;user_id=204050"'
Net::HTTP.post_form(URI.parse("http://notify.tapsense.com/ads/ping"), params)
That should more or less do it for you.

Related

Passing hidden params into url

I have a rails application in which I would like to generate a url based on a parameter, but for that parameter to be hidden from public view. So essentially working like a POST request but being able to be typed in like a GET request.
For example using a QR reader I could have the address as www.site.com/qr?lot_no=18007 but when a user scans the QR image it only shows www.site.com/qr but displays the results related to lot_no=18007.
Not sure if this is possible or not. But any help would be greatly appreciated.
If all you want to do is to prevent it from showing up in the address bar of the browser, you could use Rails.ajax to make the request dynamically through Javascript.
That will at least hide it from casual inspection, but there is no way to suppress the parameters from the query string on a GET completely, so anyone looking at the Networks tab in the browser (for example) would still see them.
Another alternative would be to encrypt the parameter value.
Maybe the Friendly id gem may be of help here
The following is an example of it's use is
http://example.com/states/washington
instead of:
http://example.com/states/4323454
This is not going to work with a post request as you mention though. It is a way of using a get request that would normally send an id in the params hash to retrieve existing records.
The gem can be found here https://github.com/norman/friendly_id
It is well maintained and up to date
Configure different route for public facing URL, the URL should include encrypted lot id as a path param.
routes.rb
get '/view_lot/:id' => 'QrCodesController#view_lot`, as: :public_view_lot
now in QrCodesController add action view_lot
def view_lot
encrypted_id = params[:id]
id = decrypt_it(encrypted_id)
#lot = Lot.find(id)
render "your_template"
end
in you QR code generation, pass URL to above action with encrypted id like public_view_lot_url(lot_id)

How to POST JSON in body for functional tests in Symfony 1.4

I'm writing some functional tests for a POST API endpoint. I've reviewed the documentation and can't find a way to add content to the POST body. The post method for sfBrowser:
post('some url',array('x'=>'y'))
Only creates POST parameters (in this case x=y). Is there anyway of adding content to the post body using sfBrowser?
From what I have found here, here and here, the POST format takes parameter:value format, so you can send your JSON with some code like:
post('some url', array('json_data' => json_encode($toJson))
and then decode in your action with
$jsonObj = json_decode($request->getParameter('json_data'));
but you need to associate your JSON data with a parameter name in your POST to retrieve it on the server side.
As a side note, after looking at the Symfony code, the parameters are given straight to $_POST except for CSRF, which is tweaked.

Passing array of parameters through get in rails

How do I pass array of parameters through Get method in rails? Currently my URL loocs like this:
http://localhost:3000/jobs/1017/editing_job_suites/1017/editing_member_jobs/new?ids[]=1025&ids[]=1027
How can I pass the array with Get method but avoid ?ids[]=1025&ids[]=1027 part.
Request is being sent with javascript window.open method. Is there any workaround to send not ajax Post request.
You should stick to using a GET request if you are not changing the state of anything, and all you want to to access a read only value.
To send an array of ids to rails in a GET request simply name your variable with square brackets at the end.
//angular snippet
$http.(method:'GET',
...
params: {'channel_id':2, 'product_ids[]': productIds}
//where productIds is an array of integers
...
)
Do not concatenate your ids as a comma separated list, just pass them individually redundantly. So in the url it would look something like this:
?channel_id=2&product_ids[]=6900&product_ids[]=6901
url encoded it will actually be more like this:
?channel_id=2&product_ids%5B%5D=6900&product_ids%5B%5D=6901
Rails will separate this back out for you.
Parameters: {"channel_id"=>"2", "product_ids"=>["6900", "6901"]}
No, GET can only put variables on the url itself. If you want the URL to be shorter, you have to POST. That's a limitation feature of HTTP, not Rails.
I recently wanted to do this and found a workaround that is a little less complex, and so has some complexity limitations but may also be easier to implement. Can't speak to security, etc.
If you pass your array values as a string with a delimiter, e.g.
http://example.com/controller?job_ids=2342,2354,25245
Then you can take the result and parse it back to what you want:
job_ids = params[:job_ids].split(',')
Then do whatever:
job_ids.each do |job_id|
job = Job.find(job_id.to_i)
end
etc
#Homan answer is valid for using an external client (e.g curl or angular). Inside Rails test cases though, you should not use []. Here's an example:
get get_test_cases_url(**path_params), params: {case_ids: ["NON-9450", "NON-12345", "NON-9361"]}
This is using new format where get_test_cases is name of route and you pass to the method all params needed to construct the URL path. Query params are a separate hash.
FYI if I use [] like case_ids[], then instead of ["NON-9450", "NON-12345", "NON-9361"] I'm getting it parsed to [["NON-9450"], ["NON-12345"], ["NON-9361"]]

Rails 3 - Friendly params in url (GET)

I have a rails 3 app and now i implementing filter for my catalog. Filters form pass data to controller through GET request. As a result i have link like this in my browser after i submit
my form (apply search):
http://localhost:3001/shoes?filter%5BShoeBottomType%5D%5B%5D=2&filter%5BShoeClassification%5D%5B%5D=1&filter%5BShoeClassification%5D%5B%5D=2&filter%5BShoeElation%5D%5B%5D=3&filter%5BShoeElation%5D%5B%5D=4&filter%5BShoeElation%5D%5B%5D=5&filter%5BShoeLiningColor%5D%5B%5D=2&filter%5BShoeLiningColor%5D%5B%5D=3&filter%5BShoeLiningColor%5D%5B%5D=4&filter%5BShoeTopColor%5D%5B%5D=1&filter%5BShoeTopColor%5D%5B%5D=2&filter%5Bonly_action%5D%5B%5D=1&page=2
Is there a way to do URL more beautiful?
PS i dont want use POST request, because I read that it is bad for SEO
TLDR: just leave it.
HTML forms serialize in a straightforward manner; the parameters are named after the HTML elements. The actual issue here is how the form elements are named. It looks like they have names like filter[ShoeBottomType][]; look into your HTML to see the name attributes. Since you're in Rails, I'm guessing you having a filter hash passed to your Rails controller method as a single argument, and since Rails expects hashes to use a certain URL format for hashes and arrays (it has to know how to deserialize it from the request), the form helper writes the form that way. And yours is especially complicated because the hash values are arrays, hence the extra set of brackets. Then it's URL encoded and you end up with an ugly mess.
You could avoid some of this problem by passing the inputs individually back to the controller instead of as a big hash. Something like:
def index
shoe_bottom_types = params[:bottom_types]
shoe_classifications = params[:classifications]
shoe_elations = params[:elations]
...
which will get you to: /shoes?bottomTypes[]=1&bottomTypes[]=2.... That doesn't seem much better, and now your controller is all gross. And I don't see how you're going to get rid of the brackets entirely if you want to have more than one of the same filter. I guess you could get crazy and do your own parsing in your controller, like breaking apart shoeBottomTypes=1|2, but then you'll have to do your own form serialization too. Again, just not worth it.
Backing up for a sec, the SEO stuff doesn't make much sense. Search engines won't fill out your form; they just follow links. The real reason you should use GET is that (presumably), submitting your form doesn't have side effects, since it's just a search. See here; it's important to use the right HTTP methods. If you use POST, you'll get weird warnings on reloads and you won't be able to bookmark the search.
Backing up even further, why do you care, especially now that SEO is out of the picture? Just as a quick demo, I did a google search for the word "thing" and this was the URL:
https://www.google.com/#hl=en&output=search&sclient=psy-ab&q=thing&pbx=1&oq=thing&aq=f&aqi=g2g-s1g1&aql=1&gs_sm=3&gs_upl=764l1877l0l1980l6l6l0l0l0l0l89l432l5l5l0&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&fp=220ef4545fdef788&biw=1920&bih=1086
So URLs for form submissions can be long. The user won't even look at it.
The only possibility I can think of for why you'd care about the length/ugliness of your URL here is that you want, separately from the form, to create links to certain searches. There are several ways to handle that, but since I don't know whether that's relevant to you, I'll let that be a follow-up.
So bottom line, it looks like I'd expect, and trying to fix it sounds ugly and pointless.
If you do not want to use a POST request, then there is no other way then to put the form values in the URL -- they have to get to the server one way or another.
On the other hand however, I do not see why doing a POST would be bad for SEO and I would love to see the article that stated so.
My suggestion is that you could add some custom routes to beautify your urls.
For example :
http://localhost:3001/shoes/Type/2/Classification/1,2/Elation/3,4,5/LiningColor/2,3,4/TopColor/1,2/only_action/1/page/2
This is far much shorter than your initial URL ;)
The counterpart is that, as far as I know, you have to use always the same order for params in your url.
The routing rule is the following :
match "shoes/Type/:type/Classification/:classification/Elation/:elation/LiningColor/:liningcolor/TopColor/:topcolor/only_action/:only_action/page/:page" => "shoes#show"
You can retrieve the passed values in params array. You have to split the string containing , in order to retrieve the multiple values.

How to get current page Url in MVC

I am writing a web app that has to deal with urls containing hash character ("#").
I am using MVC 1 with ASP.NET 3.5 (VS 2008).
My urls are like this one:
www.mysite.com/token/?name1=value1&#&name2=value2
My issue is that I cannot find a method to get the original URL, but only get the substring before the hash character:
www.mysite.com/token/?name1=value1&
I used the MVC methods provided from the class HttpRequestBase.
Anyone can suggest me an alternate method to get the entire url?
Thank you, this is my very first question!
PS: I think maybe I have to encode my hash character, isn'it?
You cannot access anything after the # from the server-side - this is all Client-side. You will need to find another way to pass the information you want through to the server.
If you are posting, you can do this with hidden fields. If you are using ajax posts, you can pass the data within the model.

Resources