fail_lord fail_lord - 1 year ago 80
Ruby Question

Routes in rails 4 with clean parameters in the url

How does routing work in rails 4? What I'm trying to achieve is urls like this:

..../categories/<name of category>

when currently i get:


html is:

<%= form_tag(categories_path, :method => "get") do %>
<%= select_tag 'category', options_for_select(@categories, params[:category]), {onchange: "this.form.submit();", prompt: "Select Category"} %>
<% end %>

and routes like this:

get '/' => '<controller>#h'
get 'categories' => '<controller>#categories'

I know i can use the gem friendly_id to style the url from category/:id to category/:category. But I'm stuck at the initial step of understanding the routes. I've tried a lot of things but its very confusing. Any ideas or suggestions would be greatly appreciated!


Answer Source

See the Routing Guide, specifically the section on Resources.

If you had in your routes.rb:

resources :categories

You could use a form helper such as:

<%= form_tag(categories_path, :method => "get") do %>
   <%= select_tag 'category', options_for_select( {|c| [, category_path(c)]}, params[:category]), {onchange: "window.location.href = this.value;", prompt: "Select Category"} %>
<% end %>

If in your Category model you added a to_param definition:

class Category < ActiveRecord::Base
  def to_param

Then all of your URLs would be as you desire, .../categories/books. The url_for helpers would generate the appropriate URLs for you:

assert category_path(@book_category) == "/categories/book"

See ActiveRecords::Integrations#to_param documentation for more.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download