views:

173

answers:

3

I am a newcomer to RoR and have a question about routing. I have set up an application and a simple user login system (yes I know there is already a login generator out there, I just wanted to try it for myself). I have a before_filter on a certain action that checks if the user is logged in or not. If not, it redirects them to the login page. This is how I have it routed, does this look right?

map.resources :user, :collection => { :login => :get }

also, why if I change

:login => :get

to

:login => :post

does it display the 'show' view?

A: 

It's close, but you may want to try:

map.resources :users, :member => { :login => :get }

They key difference is that the :collection keyword should be used when your new route is dealing with collections of that resource (such as 'index'), and not a single instance of the resource (such as a single user logging in).

Also if /users/user_id/login redirects to the login page, you're still performing a GET operation there. It's when you submit a form that you want to use a POST. So in essence you were telling Rails to expect a POST when it was receiving a GET. I can only speculate is was ignoring the login route altogether and just returning the whatever user was represented in the URL.

Bryan M.
+4  A: 
map.resources :user, :collection => { :login => :get }

will correspond to a URL like "/users/login"

map.resources :users, :member => { :login => :get }

will correspond to a URL like "/users/123/login"

Because :user is referring to a resource, it will map the url to an action depending on the request method in addition to the url.

So, the first route above will map a GET to /users/login to the login action, but when you change it to :post, it will then map a GET to /users/login to the default, which is the 'users' controller and 'show' action for a User with an ID of 'login' - which is not what you want. (and it will map a POST to /users/login to the 'login' action)

Matt Van Horn
Thanks for your answer, I actually understand the whole concept of RoR routing better now...
W_P
A: 

I'd recommend using a separate resource for your login system. A lot of people use session so you'd have

map.resource :session

You would then use the normal crud methods such as #new and #create for displaying the login form and submitting it respectively. You'll also need to create a session controller to handle these requests.

jayd