Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails : get route using controller, action & param

I am quite new to RoR and I am looking for a way of getting a route for a given controller, action & param.

Something similar to url_for() but without the domain and protocol.

Lets say I have :

params = {"controller"=>"controller", "action"=>"edit", "project_id"=>"1"}

I need to get :

route = "/controller/edit/1"

It would be best if I do not have to manually build the route and if I don't need to split the result of url_for().

Does RoR natively support such a feature? It's probably an easy question, but I couldn't find an answer.

like image 360
Alex Nault Avatar asked Dec 13 '13 19:12

Alex Nault


People also ask

How do I find a specific route in Rails?

Decoding the http request TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.

Which file can you set up your routes?

For most applications, you will begin by defining routes in your routes/web.php file. The routes defined in routes/web.php may be accessed by entering the defined route's URL in your browser.

What is the use of params in Ruby on Rails?

With params . Inside your controller action's you can call params to access form & URL query data. What is params , exactly? It's a method that returns an ActionController::Parameters object, in practice it behaves a lot like a hash.

What is the role of Rails controller?

The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions.


2 Answers

You should be able to use the following

link_to "Link Content", :controller => "my_controller", :action => "my_action", :project_id => 1

This will produce an <a> with a link to your controller/action.

like image 176
Dan Grahn Avatar answered Oct 21 '22 04:10

Dan Grahn


This is the helper that will generate a path like you want:

edit_controller_path(project_id: 1)

You can use this Helper to generate the full path (including host) of the link:

edit_controller_url(project_id: 1)

Edit : More info available at http://guides.rubyonrails.org/routing.html#path-and-url-helpers

like image 32
MrYoshiji Avatar answered Oct 21 '22 05:10

MrYoshiji