views:

63

answers:

2

My application currently has a very simple URL layout:

map.resource  :account, :controller => "users", :only => [:show, :update, :destroy] 
map.resources :workouts do |workout|
  workout.resource  :chart, :only => [:show]
  workout.resources :taggings, :only => [:destroy, :create]
end

Giving me nice easy urls for the current user. I'm now adding some public features - the ability for the public to see items. I'd like to prepend a user's login name to these URLs. At the same time, there's no need for public users to have access to anything besides the one workout resource. I'm not sure the best way to do this. I'd like to wind up with URLs that look like:

/teich/workouts/3454

Which is roughly

/:user_login/workouts/:id

Do I path_prepend? For the current user, who wants the full RESTful controls, is it best practice to still have their username prepend instead of direct URLs as I have now? Do I not worry abut all the extra routes with the path_prepend since I'll be :before permission checking anyway?

+1  A: 

Probably the easiest way to acheive something like this is to override to_param in your User model.

  def to_param
    "#{id}-#{login}"
  end

Rails uses this method when generating paths for the model. Then, when doing finds the string sends to_i which will grab the integer.

Don't forget you'll need to escape non-valid url characters too.

Ben
Thanks ben. That's not quite the solution I'm looking for. If I had a normal restful route '/users/:id/' I know I can use to_param to change that to a login. But a few differences here, primarily, I don't want the /users at the beginning.
teich
I'd have to test this (don't have the time right now), but I feel like you could create a named route 'named_user_workouts_path' something like this: map.named_user_workouts_path ':user_id/workouts/:id'. Then, in a view, you could use it like <%= link_to "#{@user.login}'s workout", named_user_workouts_path(@user, @workout) %>. Since the user model would be getting passed through the named route, to_param would be called to get the 'id'. I'd like to find this out at some point.
Ben
Thanks ben. For the sake of simplicity, I'm going with the standard routes. :) Having that /users/ just isn't going to kill me.
teich
A: 

Including URI definitions or naming conventions as part of your API violates a constraint of REST architecture. See: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

Wahnfrieden