Restricting resource routes and adding additional

2019-04-22 06:07发布

问题:

I wasn't able to find anything here or elsewhere that covered both restricting a resource's routes and adding additional non-RESTful routes in Rails 3. It's probably very simple but every example or explanation I've come across addresses just one case not both at the same time.

Here's an example of what I've been doing in Rails 2:

map.resources :sessions, :only => [:new, :create, :destroy], :member => {:recovery => :get}

Pretty straightforward, we only want 3 of the 7 RESTful routes because the others don't make any sense for this resource, but we also want to add another route which is used in account recovery.

Now from what I gather doing either one of these things is very straightforward as well:

resources :sessions, :only => [:new, :create, :destroy]

Just like in Rails 2. And:

resources :sessions do
  member do
    get :recovery
  end
end

So, how do I combine these two? Can I still use the old Rails 2 way of doing this? Is there a preferred way of doing this in Rails 3?

回答1:

You can pass arguments and a block to resources:

resources :sessions, :only => [:new, :create, :destroy] do
  get :recovery, :on => :member
end

And test it out with rake routes.



回答2:

It should be working pretty much like this

resources :sessions, :only => [:new, :create, :destroy] do
  member do
    get :recovery
  end
end

There is an even shorter way, as proposed by coreyward.

Check the rails guides, "Rails Routing from the Outside In". I also can recommend "The Rails 3 Way" by Obie Fernandez, which got 2 pretty good chapters on Routing and RESt.

Cheers