How do I forward an action to another controller in Rails? - ruby-on-rails

Rails 4 - I have an action that handles routes like www.site.com/catalog/shoes/sport/ABC123 for product and www.site.com/catalog/shoes/sport for category
The problem is I have to display some seo-paid links (not my choise, I just have to) in format www.site.com/href, and that link must me handled as some product category. That's not the only case - in future, there might be some other "short"-links, that are pointing to other parts of my site
When I used Symfony, I could just write $this->forward('controller', 'action') and get another controller's output while saving short route, but in Rails I see only redirect_to, and it does not preserve short url?
Assuming I have a route get ':href' => 'index#simple', as: :simple, how do I forward execution to another controller (or just call controller's method?), preserving original route? - In "rails way", of course
Thank you

You can just use 'redirect_to controller_action_path' / redirect_to '/controller/action' from your controller action.

Related

Ruby on Rails 4 Routing/Views/Path

I have 2 questions:
I have a controller called homepage. I have a view called samplegraph in my homepage's view directory. I want to get the routing working correctly such that www.homepage.com/samplegraph takes me to the samplegraph page.
As far as I can tell, the route for it in routes.rb should be something like this:
GET 'homepage/samplegraph' => 'homepage#showgraph1'
If I'm understanding rails routing correctly, this statement routes GET requests to homepage/samplegraph to the homepage controller's showgraph1 action. At this point I'm not particularly sure what the showgraph1 action should be in order to render the view page(samplegraph). At the moment the action is simply empty. I don't really know what to put here.
Second question:
Also, while I was researching rails routing, I was looking into resource based routing. For my purposes, I don't need most of the stuff generated by that. One thing I am interested in is that invoking resource based routing automatically generates Paths for you via helpers(I think?).
How would I generate a Path for my route, such that I'd be able to use a link_to method to link various parts of the application together? Any help/comments would be greatly appreciated.
Firstly, if you want to get 'samplegraph' page rendered by hitting 'www.homepage.com/samplegraph', you will need to update your route.
Replace
get 'homepage/samplegraph' => 'homepage#showgraph1'
with
get '/samplegraph' => 'homepage#showgraph1'
Now in showgraph1 action of your homepage controller, you will need to render samplegraph view page at last line of the action.
render 'samplegraph'
As of you second question, just hit rake routes on your terminal from your app directory. It will show all routes with helpers which you can use with link_to. You will need to append _path to those routes while using with link_to
Like #RAJ said first of all you need to change your route to
get '/samplegraph' => 'homepage#showgraph1'
At this point I'm not particularly sure what the showgraph1 action should be in order to render the view page(samplegraph)
Rails doesn't care if your action is empty or not, it'll still render your actions view even if it's empty. Since your action is named showgraph1 so it'll make rails look for showgraph1.html.erb with path views/homepage/showgraph1.html.erb
To change this behavior you need to use render 'samplegraph' in your action
One thing I am interested in is that invoking resource based routing automatically generates Paths for you via helpers(I think?)
Rails generate path and url helpers for each route and it doesn't depend on how your routes are defined but you can customize your helper methods by specifying as: option
get 'homepage/samplegraph' => 'homepage#showgraph1', as: 'showgraph'
This will make your helper methods showgraph_path and showgraph_url

what are the sequence of events that happen when you get a page

Im trying to get my head around the sequence of events that happen between when rails receives a get/post command and the page is served. I was just trying to map out the sequence myself and i realised i dont fully understand myself which scripts is even ran first so I'd like to clear it up in my head.
many thanks
jon
The request goes into the route matcher which parses the URL, parses the config/routes.rb and if the URL matches a route, it looks for a controller file whose name matches the controller part of the URL, (e.g. http://localhost/categories will look for a CategoriesController)
Then, one of two things happen:
If you're using a Rails restful route, the route matcher applies heuristics to figure out which of the 7 actions to call: a GET on a plural last part is mapped to index; a GET mapped to an ID-looking part after the plural is mapped to show (e.g. categories/1 or categories/something or categories/1-something); a POST to a plural last part is mapped to create; a PUT to an ID-looking part after the plural is mapped to update; a DELETE to the same URL is mapped to destroy; new and edit are mapped to GETs for categories/new & categories/edit.
If you have a custom action, you must have a method in your controller object of the same name.
The chosen action is executed and then Rails either renders the template/file/action specified in the render call within the action or it looks for a view file of the same name as the action and that ends with .html.erb (by default) in the app/views/ directory.
Simple.
Rails does quite a lot of things, a good way to get a decent overview is to read the "Action Controller Overview" document at rails guides: http://guides.rubyonrails.org/action_controller_overview.html
The basic structure is:
rack middleware
routing
filters
controller code
rendering
filters
But rails also does many things by itself to the request. It automatically determines what kind of response you want based on your accept headers, and/or if you manually specify which type of response you want with a file ending like /blog/1.xml. Rails also magically creates a nicely formatted params hash, parsing params like user[name]=foo to {:user => {:name => "foo"}}. Rails also has built-in exception handling and some nice stuff to prevent cross site request forgery and much more, so check out the Controller Overview for the lowdown on that.

Create a routes to a controller without model with a /id

I have product with a foreign collection_id key
I want to pass an id to a controller.
To do so i have the following routes for my controller :
controller :magasin do
get "magasin" => "magasin#index"
end
The only view in my controller is magasin/index.html.erb
The link to magasin is link_to collection.nom, magasin_path(collection)
This kind of syntax usually works in controllers with models. Here my link is : http://localhost:3000/magasin.2 instead of http://localhost:3000/magasin/2
Later on i will need to call the same view with product_kind_id instead of collection_id and i will add sort by name/price ....
How can i have the ID as a normal argument (/:id)instead of a type(.id)?
A popular URL schema to follow is RESTful routing. Rails has this built-in and will set it up for you if you initialize your resource via rails generate scaffold Magasin nom:string.
If you put resources :magasins in your routing file, it will route /magasins to MagasinsController#index and /magasins/1 to MagasinsController#show with params[:id] set to "1". It will also set up a few other routes that will be useful in the future but for now will just raise an action not found exception.
You don't want to use the dot as an argument delimiter, since Rails places what comes after the dot in the request.format method or just in params[:format] (ordinarily accessed through the respond_to method that comes with the generated scaffolds). Save that dot for later when you are working on delivering alternative display formats like XML and JSON.
I realize I've said a lot in a small space, so feel free to ask any follow up questions once you've consulted the Rails Guide on the issue, and I'll be very glad to help!

Rails way of constructing & redirecting to an url with post parameters of a form

I would like to do that's the best way of actually accomplishing the
following on Rails.
I have a "Booking Form" with 5 fields (Property, Amount of Children,
Amount of Adults and 2 Dates - Departure and Arrival) based on these
fields, I need to construct an URL and redirect the user to this url.
Now, I have 2 questions.
1) How i catch the POST parameters in the controller, because I'm
mapping the form to an action like this:
<% form_tag(:action => "booking") do %>
and routing it to a controller action like this: (Pages Controller,
Booking Action)
match 'pages/booking' => 'pages#booking'
2) Is this the Rails way of actually accomplishing such thing?
I did it this way in PHP in the past, but now I have the need of
actually doing it in Rails, could you Rails Gurus inspire me ?
To access parameters in the controller, even ones submitted in a POST body, use the params hash. Eg: params[:form_field]
To redirect to another URL using a controller, use redirect_to. You can certainly use the values in params to construct a URL and pass it to redirect_to.
If you're using resourceful routes, which is the best way to go about such things, you would route things through the traditional approach:
resources :bookings
Then you'd post the form to bookings_path and it would all work out, as that's BookingsController#create. It's always better to have a strong correlation between model and controller where possible.
The resources definition in routes.rb helps you by creating all the default RESTful actions which you can build off of. If you really need a custom route, you can always rename it using the :as option, or route it independently.
If you go about creating your own arbitrary routes, such as /pages/booking you're going to create quite a mess that someone else will have to maintain. Quite often that someone else is you in the future.

hyperlink in ruby on rails

This is something probably trivial but i can't quite find my way round it:
How do i add a hyperlink from one ruby-file.html.erb to another please?
Ruby uses something called routes. You can create named routes for some operations or you can use resource routes (autogenerated CRUD per resource).
For example if you have route for a model called Car, then calling
link_to "Edit my car", edit_car_path(#car)
in your view will generate a link.
remember that your are linking to a controller action in model/view/controller and not to pages

Resources