Search code examples
ruby-on-rails-4rails-routing

Rails 4 dynamic routing


I have a site that shows content about Summer/Winter sports. So the contents are split into categories, let's say the route /skiing goes to content related to ski, /windsurfing shows windsurfing content and so on. Now, I am envisioning creating an admin panel of some sort where I can add an arbitrary category that didn't exist before, let's say "Snowboarding", this would create a link called /snowboarding that would then show content tagged with snowboarding.

So, in order to achieve this in Rails, is it better to have a general controller (let's call it PageContentController) and a generic routing configuration in routes.rb like: match ':controller(/:action(/:id(.:format)))' , or is there a better way to create new routes on the fly?

Thanks.


Solution

  • I think you are over-thinking this too much when looking for dynamic routing (creating route on the fly).

    You could simply create a resource called Sport (rails g scaffold sport) this will create for you:

    • A sport model
    • A SportController
    • Views related to the management of sports (Index, Create, Read, Update, Delete)
    • Add an entry to routes.rb such as resources :sports (this will create all necessary routes for CRUD)

    From there you can dynamically create display all sports on index page accessible on /sports/index Display a sport at /sports/:id or use a friendly url to display the sport name instead of an id.