REST Rails 2 nested routes without resource names? - ruby-on-rails

I'm using Rails 2.
I have resources nested like this:
- university_categories
- universities
- studies
- professors
- comments
I wish to use RESTful routes, but I don't want all that clutter in my URL. For example instead of:
/universities/:university_id/studies/:study_id/professors/:professor_id
I want:
/professors/:university_id/:study_id/:professor_id
(I don't map professors seperately so there shouldn't be a confusion between this and /professors/:professor_id since that route shouldn't exist).
Again, I want to use RESTful resources/routes...
Also note, I am using slugs instead of IDs. Slugs for studies are NOT unique, while other are. Also, there are no many-to-many relationships (so if I know the slug of a professor, which is unique, I also know which study and university and category it belongs to, however I still wish this information to be in the URI if possible for SEO, and also it is necessary when adding a new professor). I do however want to use shallow nesting for "administrator" URIs like edit, destroy (note the problem here with Study since it's slug is not unique, though)...
I would also like some tips on how to use the url helpers so that I don't have too much to fix if I change the routes in the future...
Thank you.

It doesn't seem like map.resources will provide you with this functionality, but you could use something like (untested)
map.show_professor "/professors/:university_id/:study_id/:professor_id", :controller => "professors", :action => "show"
and then similar routes for the other actions.
There might be a better solution, but this is the only way I can find that would work, since it seems map.resources assumes it is in the form of /resources/(:resource_id)
You can use REST this way, you just have to do all the actions yourself instead of using the shortcut.
As an example of an edit, you can just use
map.edit_professor "/professors/:id/edit", :controller => "professors", :action => "edit"

Related

Self nested infinite routes

Is there a way to self nest a resource in the routes infinetelly?
Suppose the following scenario: I want to create several pages that may be self nested one to another, like a products page has many product pages and each product page has several sub-pages etc.
The resource would be a page in a tree structure , like with the awesome nested set gem.
In case an admin can create pages at unknown depth level how would I make the routes?
The above example has to produce a url like /:friendly_id_of_level_1/:friendly_id_of_level_2/.../:friendly_id_of_level_n
I've tried going with dynamic routes but it has many drawbacks this way.
Any suggestions?
I do a similar thing to this in one of my apps with this route:
map.connect "/c/*modules", :controller => "content", :action => "show"
(Note this is using rails2 routing syntax, you might need to update it).
This will resolve this url
/c/123-foo/456-bar/789-baz/653-qux
to the content#show action, with params set like
params = {"modules"=>[123-foo", "456-bar", "789-baz", "653-qux"]}
The modules are in a tree structure, so i can use the sequence of module ids in params[:modules] to make a breadcrumb chain and any other heirarchical data, and i use the last one in the array as the "current" one to actually show to the user.
Note: I put the "/c/" at the start of the url to separate these nested routes out from all my other routes: otherwise it's very greedy and will match pretty much any url on your site. That's not a problem if you want to always have it as your "catchall" route down at the bottom of your routes file, but if not then you'll need to add something to make it distinct. Obviously this doesn't need to be "/c/", you could have anything which will stop it colliding with your other routes.

Remove controller_name from URL in Rails 3 and use custom string instead of id

Since the beginning I always hat this one problem with rails, short urls without the controller name.
For example, I have a blog and I don't want any dates or controller names in the url, I already have a Page model with a unique field url in my database. Rails works great with such urls:
jeena.net/pages/1
And when I modify the model I even can get it to use
jeena.net/pages/foo
But it seems not to matter what I do I can not get it to work with just:
jeena.net/foo
Of course I want the index page still to work with
jeena.net/pages
And I want creating new pages and updating old pages to work too in some was as well as the link_to()-method. All suggestions are appreciated.
To define that route, try adding the following to your routes.rb:
match '/:id' => 'your_controller#your_action'
This will pretty much match everything to the id of your model. And that's not very nice... You don't want to route youe_host/pages to the pages controller, with an id equal to 'pages'... To prevent that from happening, make sure to put that line on the end of the routes.rb file. The router uses the first route that matches the path received, so putting that line on the end of it will make sure that it will only match your route after it ran out of other meaningful options.
A better practice would be to pass regexp constraints to the router, so that it will only match ids with a specific format, like that:
match '/:id' => 'your_controller#your_action', :constraints => { :id => /your_regexp/ }
Refer to the guides if you have doubts about the rails rounting system. It is pretty well written and covers lots of important things.
Rails rounting - Official Guides
edit: to create a named route, one that you can call in your controllers and override the normal routes that you are probably creating with resource, you have to provide the :as => parameter in your routes.rb
match '/:id' => 'your_controller#your_action', :as => some_name
Then you'll be able to call it in your controller/views like this:
link_to some_name_path(#my_string_id)
Hope this helps. And take a time to read the guides, it has really lots of useful info, including more details about creating named routes.

How to handle unpredictable routes?

Assume the following paths to be legitimate and resolving:
http://test.local/wizards/home
http://test.local/wizards/wizardfest2012/dates
http://test.local/dragons/
http://test.local/dragons/blog/stop-slaying-us
http://test.local/
This is (if you couldn't tell) for a CMS that includes a blog, so the slugs would be generated by the user. I have some routes to process first for reserved namespaces (admin, for example).
I assume that the user generated routes need to be routed to a Page controller - but, I don't think pragmatically adding a line to routes.rb is efficient. My question then, is how do I process the first part of the params (in this case, wizards and dragons) to get the correct information from the model?
Here's one of my ideas - split (somehow) the first part of the slug (again, wizards and dragons and pass the rest of the slug (for example, /wizardfest2012/dates) to the model to fetch the associated content.
Any thoughts on the most efficient way to do this?
I am not sure whether I understand what you want to achieve, but maybe this is what you want:
constraints :camp => /wizards|dragons/ do
match ':camp/home' => "pages#home"
match ':camp/blog/:title' => "pages#blog"
# ...and all the routes with known components
match ':camp/*other' => "pages#other"
end
You may create a before_filter which will recognize the params[:camp] and prepare the necessary models or whatever is needed.
The other action will receive the string "wizardfest2012/dates" as params[:other]. I hope that it was what you needed.
The "Rails Routing from the Outside In" guide may be worth reading, unless you have already read it.

Rails: resources for unorthodox urls?

I'd like to have a URL like this:
/payroll/region/1
and I'd like it to map to the Tasks Controller's payroll_list function. I'd also like to use REST. What's the best way to do this?
Many thanks!
Well I'd suggest you better go with the convention how Rails handles this. If you still insist on using such "strange" URLs and want to ignore the problems/headaches this can create during further development, then try to use Refraction.
I don't want to be rude but currently it seems to me that you did not understand why restful URLs are the way they are. Please do understand the design behind this first, then rethink your application/controller and routing design. I bet you will be enlighted.
In this example, your URL should probably be /regions/1/payrolls with map.resources :regions, :has_many => :payrolls. Then your payroll list would be rendered by the PayrollsController having a params[:region_id] - and that actually makes sense (and probably what you tried to achieve with your URL layout). Code snippet:
def index
if params[:region_id]
#region = Region.find(params[:region_id])
#payrolls = #region.payrolls
else
#payrolls = Payroll.all
end
end
If you still want to have a resource under a different named URL, use the following:
map.resources :regions do |regions|
regions.resources :tasks, :as => :payrolls
end
This will map the nested resources to the tasks controller using the named URL part "payrolls." But this probably does not work as you might expect because restful logic means you should handle the payroll model in the PayrollsController. Otherwise you might run into strange looking code. Maybe your design of the TasksController is just wrong? Rails will probably expect tasks to be handled over to your tasks controller although you name it payrolls. This can be confusing at least (however, it does not actually expect these being task models, so it will probably work).
BTW - Keep in mind: "restful" also means your application should answer to standard verbs on a resource, not just using "resourceful" routes. It's also about the GET, PUT, DELETE and POST http verbs, and of course the "edit", "new" etc default actions. Do not try to make your controllers big and complicated. Follow the motto "skinny controllers - fat models".
OK, so a better question, then might be this:
How can I get it so that I use your suggestion:
/regions/1/payroll
and have that map RESTfully to:
Tasks controller with index, new, etc that are prefixed by "payroll_"?
Like this: TasksController#payroll_index or TasksController#payroll_new

Can someone please explain to me in clear, layman's terms what the deal is with mapped resources and named routes in Ruby on Rails?

I've been using Ruby for the first time on a project at my work, so I am still somewhat learning the ropes (and loving every minute of it).
While I understand the point of the map.connect functions in the route.rb file, I don't understand the "resources" and "named route" features of Rails. I have my Rails book here and read it over several times, but I still don't get it. The named routes I kinda get - I think that they are either rules, either explicitly defined, or calculated by a code block, but the resources are a complete mystery to me; the only thing I've gleamed rom them is that you just NEED them if you want some of the cool stuff to work, such as being able to call 'resource_path' (and its awesome related family of methods).
My current project has:
map.resources :application_forms
map.resources :sections
map.resources :questions
map.resources :seed_answers
map.resources :question_types
map.resources :form_questions
map.resources :rules
map.resources :form_rules
..but my Rails book has this awesome kinda "has_many" and "only" type hashes and parameters hanging off them and I can't work out exactly when I am supposed to use them, nor what the benefit is.
Can anyone set me straight?
Named routes are just that; a route with a name attached, so that you can easily refer to it when you want to generate a URL. Among other things, it can eliminate ambiguity.
A resource is basically a 'thing' that you want to have routes to manipulate. When you define that 'sections' is a resource, what you're doing is saying "I want a route to get all the sections. I want a route to add a new section. I want a route to edit an existing section. I want a route to delete a section." That sort of thing. These routes point to standardized method names like index, new, edit, and so on. Each of these routes will have a name assigned based on what it is; so there is now a route named 'edit_section'.
The :has_many parameter lets you say that a certain kind of thing has sub-things. For example, you can say map.resources :sections, :has_many => [:questions]. This means that a question belongs to a section, and this will be reflected in the url and the route. You'd get urls like '/sections/27/questions/12' and named routes like 'section_questions'.
The :only parameter says "only make routes for these actions"; you could use it if you only want to allow listing, viewing, and adding items, not editing or deleting.
Honestly the Rails Routing Guide will give you a good explanation in about as plain wording as you can get. Just know that a resource route == RESTful route and you're good to go.
We all struggled with understanding resources and REST when DHH introduced it to the Rails community at the first RailsConf in 2006, so it is not wonder you have trouble grasping the concept.
I admit there is much better and more up-to-date explanations of the concepts today, but back then, right after David's keynote, I wrote a blog post in which I, from discussion with other conference attendees, tried to understand and explain it. It might help you, as it doesn't take for granted that you know everything about REST as more recent articles do.

Resources