How do I get only the query string in a Rails route? - ruby-on-rails-3

I am using a route like this
match "/v1/:method" => "v1#index"
My intention here is capture the name of the api method and then send the request to that method inside the controller.
def index
self.send params[:method], params
end
I figured this would send the other parameters as an argument to the method, but it didn't work. So my question is how can I pass the non-method parameters in a query string?

#query_parameters does exactly what you want:
request.query_parameters
It's also the most efficient solution since it doesn't construct a new hash, like the other ones do.

Stolen from the work of a colleague. I find this a slightly more robust solution, since it will work even if there are changes to the path parameters:
params.except(*request.path_parameters.keys)

I sort of solved this problem by doing this:
params.except("method","action","controller")

Related

Recursive/Exploded uri variable with restlet

Does Restlet support exploded path variable (reference to URI Template RFC)?
An example would be /documents{/path*} where path can be for example "a/b/c/d/e".
This syntax doesn't seem to work with Restlet.
I'm creating a folder navigation api and I can have variable path depth, but I'm trying to have only one resource on the server side to handle all the calls. Is this something I can do with Restlet? I suppose I could create a custom router but if there is another way to do this I would like to know.
Thanks
It is possible to support this using matching modes.
For example:
myRouter.attach("/documents{path}",
MyResource.class).setMatchingMode(Template.START_WITH);
Hope this helps!
I'm doing the following
myRouter.attach("/documents/{path}", MyResource.class).setMatchingMode(Template.START_WITH);
Now I do get inside the resource GET method, but if I request the value of the path variable, I only get the first part (for example, /documents/a/b/c, path returns "a".) I use getRequest().getAttributes().get("path") to retrieve the value. Am I doing something wrong ?
Mathieu

MVC multiple parameter routing

I've been trying to pull the parameters passed into a page so I can post it back in Context.
So far,
ViewBag.Message = string.Format("{0}::{1}::{2}",
RouteData.Values["controller"],
RouteData.Values["actions"],
RouteData.Values["id"]);
works with anything simple like "66" or "tt" but anything more complex like "?name=blargh?viewId=66" and it fails.
I've tried a bunch of different ways to see if I could strike gold but nothing seems to work so does anybody have any idea what I'm missing/doing wrong/should be doing instead?
" but anything more complex like "?name=blargh?viewId=66" and it fails.
This doesn't seem to be routing information but query string which you should retrieve from the Request.QueryString bag.
If the {id} parameter is part of your route (as the default routes {controller}/{action}/{id}) I hope you realize that this id cannot be anything you like just because there are rules for an url. For example it cannot contain ? because this symbol has an entirely different meaning in an url - it represents the query string separator.

How can I access query string parameters for requests I've manually dispatched in Laravel 4?

I'm writing a simple API, and building a simple web application on top of this API.
Because I want to "consume my own API" directly, I first Googled and found this answer on StackOverflow which answers my initial question perfectly: Consuming my own Laravel API
Now, this works great, I'm able to access my API by doing something like:
$request = Request::create('/api/cars/'.$id, 'GET');
$instance = json_decode(Route::dispatch($request)->getContent());
This is great! But, my API also allows you to add an optional fields parameter to the GET query string to specify specific attributes that should be returned, such as this:
http://cars.com/api/cars/1?fields=id,color
Now the way I actually handle this in the API is something along the lines of this:
public function show(Car $car)
{
if(Input::has('fields'))
{
//Here I do some logic and basically return only fields requested
....
...
}
I would assume that I could do something similar as I did with the query string parameter-less approach before, something like this:
$request = Request::create('/api/cars/' . $id . '?fields=id,color', 'GET');
$instance = json_decode(Route::dispatch($request)->getContent());
BUT, it doesn't seem so. Long story short, after stepping through the code it seems that the Request object is correctly created (and it correctly pulls out the fields parameter and assigns id,color to it), and the Route seems to be dispatched OK, but within my API controller itself I do not know how to access the field parameter. Using Input::get('fields') (which is what I use for "normal" requests) returns nothing, and I'm fairly certain that's because the static Input is referencing or scoping to the initial request the came in, NOT the new request I dispatched "manually" from within the app itself.
So, my question is really how should I be doing this? Am I doing something wrong? Ideally I'd like to avoid doing anything ugly or special in my API controller, I'd like to be able to use Input::get for the internally dispatched requests and not have to make a second check , etc.
You are correct in that using Input is actually referencing the current request and not your newly created request. Your input will be available on the request instance itself that you instantiate with Request::create().
If you were using (as you should be) Illuminate\Http\Request to instantiate your request then you can use $request->input('key') or $request->query('key') to get parameters from the query string.
Now, the problem here is that you might not have your Illuminate\Http\Request instance available to you in the route. A solution here (so that you can continue using the Input facade) is to physically replace the input on the current request, then switch it back.
// Store the original input of the request and then replace the input with your request instances input.
$originalInput = Request::input();
Request::replace($request->input());
// Dispatch your request instance with the router.
$response = Route::dispatch($request);
// Replace the input again with the original request input.
Request::replace($originalInput);
This should work (in theory) and you should still be able to use your original request input before and after your internal API request is made.
I was also just facing this issue and thanks to Jason's great answers I was able to make it work.
Just wanted to add that I found out that the Route also needs to be replaced. Otherwise Route::currentRouteName() will return the dispatched route later in the script.
More details to this can be found on my blog post.
I also did some tests for the stacking issue and called internal API methods repeatedly from within each other with this approach. It worked out just fine! All requests and routes have been set correctly.
If you want to invoke an internal API and pass parameters via an array (instead of query string), you can do like this:
$request = Request::create("/api/cars", "GET", array(
"id" => $id,
"fields" => array("id","color")
));
$originalInput = Request::input();//backup original input
Request::replace($request->input());
$car = json_decode(Route::dispatch($request)->getContent());//invoke API
Request::replace($originalInput);//restore orginal input
Ref: Laravel : calling your own API

How do I do a redirection in routes.rb passing on the query string

I had a functioning redirect in my routes.rb like so;
match "/invoices" => redirect("/dashboard")
I now want to add a query string to this so that, e.g.,
/invoices?show=overdue
will be redirected to
/dashboard?show=overdue
I've tried several things. The closest I have got is;
match "/invoices?:string" => redirect("/dashboard?%{string}")
which gives me the correct output but with the original URL still displayed in the browser.
I'm sure I'm missing something pretty simple, but I can't see what.
You can use request object in this case:
match "/invoices" => redirect{ |p, request| "/dashboard?#{request.query_string}" }
The simplest way to do this (at least in Rails 4) is do use the options mode for the redirect call..
get '/invoices' => redirect(path: '/dashboard')
This will ONLY change the path component and leave the query parameters alone.
While the accepted answer works perfectly, it is not quite suitable for keeping things DRY — there is a lot of duplicate code once you need to redirect more than one route.
In this case, a custom redirector is an elegant approach:
class QueryRedirector
def call(params, request)
uri = URI.parse(request.original_url)
if uri.query
"#{#destination}?#{uri.query}"
else
#destination
end
end
def initialize(destination)
#destination = destination
end
end
Now you can provide the redirect method with a new instance of this class:
get "/invoices", to: redirect(QueryRedirector.new("/dashboard"))
I have a written an article with a more detailed explanation.

How to pass URL parameters to the root [in the routes.rb] in Ruby on Rails

realize this question is similar to this one.
Pass URL parameters to a redirect_to :root
However, I'm wondering to start the application with parameters passed at the outset. Perhaps root :to in the routes.rb file is not exactly the correct way to go?
Was basically hoping that it would start like this.
http://localhost:3000/controller?hello_id=1&finder_id=1&laser_id=1&sharks_id=4
Any thoughts would be really appreciated!
Perhaps it has changed in the last couple years, but this is definitely possible now:
root to: 'controller#action', hello_id: 1, finder_id: 1, laser_id: 1, sharks_id: 4
It seems it is impossible to do so in rails.
One way to workaround this is to point to an action of controller that will redirect to another action with all the parameters set (uglier solution, uglier solution in my opinion)
or
you can point to a controller that will set default values to the parameters if no parameters were passed.