Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting resource routes and adding additional non-RESTful routes in Rails 3

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?

like image 869
seaneshbaugh Avatar asked Jun 19 '11 19:06

seaneshbaugh


People also ask

What is the difference between resources and resource in Rails?

Difference between singular resource and resources in Rails routes. So far, we have been using resources to declare a resource. Rails also lets us declare a singular version of it using resource. Rails recommends us to use singular resource when we do not have an identifier.

How many types of routes are there in Rails?

Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.

What are resources in Rails routes?

Any object that you want users to be able to access via URI and perform CRUD (or some subset thereof) operations on can be thought of as a resource. In the Rails sense, it is generally a database table which is represented by a model, and acted on through a controller.


1 Answers

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.

like image 93
coreyward Avatar answered Nov 15 '22 19:11

coreyward