Complex Rails Routing
I would like to do something like github has with nested urls, and like How do I route user profile URLs to skip the controller? but not really sure how to go on with it.
For example, looking at a commit they have: ':user/:repo/commit/:sha', with th开发者_高级运维e controller being commit. How would I replicate this type of nested resource?
thank you :)
If commit is a RESTful controller that uses :sha instead of an id to find records. You could do this instead:
map.resource :commits, :path_prefix => ':user/:repo', :as => 'commit'
It will create the standard RESTful routes that look like http://yoursite.tld/:user/:repo/commit/:id
Again, if you'll never be translating the id portion in the url to a commit id, then there's no reason you can't use it as a :sha value.
example:
class CommitController < ApplicationController
def show
@commit = Commit.find(:first, :conditions => {:sha => params[:id]})
end
...
end
You may also want to over ride to_param in the commit model to return the sha value.
class Commt < ActiveRecord::Base
...
def to_param
sha
end
end
So that now link_to commit_url(@commit, :user => current_user, :repo => @repo)
will provide a url that matches your scheme.
How about
map.connect ':user/:repo/commit/:sha', :action => :index
Or use map.resource
instead of map.connect
if you need a RESTful route.
In the controller, the URL information can be retrieved from params, for example params[:user]
returns the username.
You can name your routes as you like, and specify which controllers and actions you'd like to use them with.
For example, you might have:
map.connect ':user/:repo/commit/:sha', :controller => 'transactions', :action => 'commit'
This would send the request to the 'commit' method in 'transactions' controller.
The other variables can then be accessed in your controller using params:
@user = User.find(params[:user])
@repo = Repo.find(params[:repo])
精彩评论