fail_lord fail_lord - 4 months ago 19
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:

..../categories?utf8=✓&category=dingus


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!

Thanks!

Answer

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(@categories.map {|c| [c.name, 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
    name
  end
end

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.

Comments