Search code examples
ruby-on-railsruby-on-rails-3routesnamed-routing

Is it possible to specify a named route within a resourceful route?


I'm just upgrading my app to Rails 3 and as I have to rewrite my routing anyway, I'm taking some time to improve my named routes.

I have an invoices controller which has a trash action (/invoices/trash lists all invoices in trash). I want to access this through a named route (i.e. trash_url) for simplicity in my views.

I can achieve this easily enough with the following

match "/invoices/trash" => "invoices#trash", :as => :trash

What I want to know is if there is a way of doing this within the block where I define the routes for my invoice controller. I have tried the following and it doesn't work.

resources :invoices do
  collection do
    get :trash, :as => :trash
  end
end

Is what I am trying to do possible or do I have to define my named route outside of this block?

Thanks.


Solution

  • The method you list (shown below) works fine for me, it generates trash_invoices_path and trash_invoices_url helper methods.

    resources :invoices do
      collection do
        get :trash, :as => :trash
      end
    end
    

    You can make methods in your application controller named trash_url and trash_path that just call and return the path from the generated methods mentioned above if you have a need to use those specific method names instead of the generated ones.