views:

280

answers:

1

Hello,

I am relatively new to ruby on rails, so this question might be easy. Rails does a lot of magic and I am not sure where to look up such things, because I don't know which part of the framework is to blame.

I basically did the authlogic_example and fiddled around with the code afterwards. My routes.rb looks like this

 map.root :controller => "user_session", :action => "new" # optional, this just sets the root route
 map.resources :users
 map.resource :user_session

As you can see, I have a controller called *user_session*. *user_session* has three actions new, create and destroy. I can reach the controllers at

 localhost:3000/user_sessions/[new,destroy,create].

I can also reach the new action at

 localhost:3000/user_session/new

for destroy or create I get a routing error here. According to the documentation the first case should be the standard one: "A singular name is given to map.resource. The default controller name is still taken from the plural name."

My problem now is that link_to only takes the singular of the controller name, where I can only reach new, but not destroy

<%= link_to "singular", :controller=>"user_session", :action=>"destroy" %> 
#=> http://localhost:3000/user_session/destroy
<%= link_to "plural",   :controller=>"user_sessions", :action=>"destroy" %>
#=> http://localhost:3000/user_session

This is pretty confusing and is not even close to what I expected, but also causes problems: I can't

redirect_to :controller=>"user_sessions", :action=>"destroy"

because I get redirected to

http://localhost:3000/user_session

As I already mentioned, I am pretty new to rails, so I might not have the right way of thinking yet. Can you point me to anything that describes this behaviour? How would I resolve this issue?

+1  A: 

The behaviour you describe is correct. At least for RESTful routing. Where the action to take is linked to the request type.

a POST request on http://localhost:3000/user%5Fsession will create a session. While a DELETE request on the same URI will destroy the session.

If you're mapping resources you should be using the convenience methods, to abstract most of that out.

<%= link_to "Login", create_user_session_url %>

However, map.resources doesn't provide a destroy helper. So you will either have to make one or explicitly mention :method => :delete

<%= link_to "Logout", {:controller => "user_sessions", :action => :destroy}, :method => :destroy %>

I prefer the named route version where this goes in config/routes.rb

map.logout '/logout', :controller => "sessions" , :action => :destroy

Then just use this in my views:

<%= link_to "Logout", logout_url %>
EmFi
Works. Thanks. ;-)
sebastiangeiger