Search code examples
ruby-on-railsruby-on-rails-3actionview

Rails link_to to generate URL with subdirectory


In my routes file I have the line:

match 'documents/:category/:id' => 'documents#show'

allowing me to use URLs like:

*localhost:3000/documents/lesson_plans/day_01*

The URL works correctly, but I can't figure out how to generate it using link_to.


link_to 'day_01', document_path('/lesson_plans/day_01')

returns the error:

No route matches {:action=>"show", :controller=>"documents", :id=>"/lesson_plans/day_01"}


link_to 'day_01', document_path(:category => 'lesson_plans', :id => 'day_01')

works, but it generates the URL:

localhost:3000/documents/day_01?category=lesson_plans

which isn't clean enough.


Is there a way to generate the URL:

localhost:3000/documents/lesson_plans/day_01


Solution

  • Give this a try:

    match 'documents/:category/:id' => 'documents#show', :as => :document
    

    and

    = link_to 'day_01', document_path('day_01', :category => 'lesson_plans')
    

    It should generate:

    http://localhost:3000/documents/lesson_plans/day_01