Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Rails named route helpers with parameters?

given this route

match 'posts/hello/:name/:title' => 'post#show', :as => :hello 
  • what are the ways that I can call hello_path ?

  • if i call hello_path(@post), what does it try to do?

I was hoping that the :name and :title files will bind to the path automatically but it seems that rails only know how to get the :id out of the model object.

instead, it only works if I call it like

<%= link_to "link2", hello_url(:name=> @post.name, :title=>@post.title) %> 

(lack of proper documentation is really killing me)

like image 244
Ant Avatar asked Dec 16 '11 07:12

Ant


People also ask

How do you pass parameters in Rails?

What you would like is to pass account_id as a url parameter to the path. If you have set up named routes correctly in routes. rb, you can use path helpers. And you need to control that account_id is allowed for 'mass assignment'.

What is Route helper in Rails?

Under the hood, Rails path helpers use ActionDispatch to generate paths that map to routes defined in routes. rb . When the path helper is not provided the necessary route key, two outcomes may occur: 1) The missing route key is filled in based on the current request.

How do Rails routes work?

Rails routing is a two-way piece of machinery – rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.


1 Answers

To answer your two questions:

  • At the command line, runrake routes to see what routes there are in your app. It will show you all the ways you can use the named routes, just add "_path" or "_url" to the name of the route which is shown on the left.
  • Calling hello_path(@post) will generate a URL to the show page for that hello instance.

The way you are calling it is the norm:

<%= link_to "link2", hello_url(:name=> @post.name, :title=>@post.title) %> 

However, this may work too:

<%= link_to "link2", hello_url(@post.name, @post.title) %> 

Here is some documentation (other than the Rails API) which should help. http://guides.rubyonrails.org/routing.html

like image 175
GregT Avatar answered Sep 23 '22 07:09

GregT