i have a task to create mapping of different urls at run time .
In the application i have a GUI interface which displays list of routes from routes.rb file.
User has the ability to change that url to some different name from the interface
eg. (abc/mno) --user can change them to --(hello)
so if user type /hello in the browser request is redirected to /abc/mno
i have to store those mapped routes in a database.
how to add a dynamic mapped route to already defined routes(routes.rb) while creating a new record in database
how to add routes from the database while loading routes.rb file.
i am not able to figure out how to extend the default router so that it can include routes from the database ..
Asked
Active
Viewed 2,556 times
3

Sanjeev
- 298
- 4
- 11
2 Answers
1
I don't have a complete solution for you, but you can start with two approaches:
- Use custom URL constraint: Dynamic URL -> Controller mapping for routes in Rails
- Use Rack middleware: Dynamic Rails routing based on database

Community
- 1
- 1

Blue Smith
- 8,580
- 2
- 28
- 33
-
problem of creating a controller that handles all routing is that .. when user creates a mapping from gui that mapping is not reflected until i restart my server again..different path_helpers are also not available – Sanjeev May 15 '13 at 09:40
-
@BlueSmith The second link posted by BlueSmith is pretty much dead on. The example shown is a good starting point, the changes should be straightforward to do what you want. – RadBrad May 20 '13 at 15:38
1
If you don't want to use rack middleware, you can use constraints. Hopefully, your dynamic routes are scoped to something, like "/abc/anything-after-here-can-be-dynamic", as opposed to straight off the root...
So, lets say you wanted dynamic routes based upon User's first name, then you would do the following:
#config/routes.rb
match '/abc/:route' => "abc#dynamicroute", :contraints => DynamicRouteConstraint.new
#lib/dynamic_route_constraint.rb
class DynamicRouteConstraint < Struct.new
def matches?(request)
User.find_by_first_name(request.params[:route]).present?
end
end
#app/controllers/abc_controller.rb
class AbcController < ApplicationController
def dynamicroute
@user = User.find_by_first_name(params[:route])
#render or redirect, however you wish
end
end

Peter P.
- 3,221
- 2
- 25
- 31
-
You don't need to instantiate a new object, you could just call a class method. +1 to your answer because it inspired me to implement my own solution! – Cyzanfar May 07 '17 at 03:32