I'm linking to the destroy action for the Sessions controller like this:
<%= link_to "Sign out", session_path, method: :delete %>
Routes.rb:
resources :sessions, only: [:new, :create, :destroy]
Rails complains about the link above:
No route matches {:action=>"destroy", :controller=>"sessions"} missing required keys: [:id]
How do I link to the destroy action and keeping the REST/resource methodology in Rails when there's no object ID to provide for the link?
destroy
is a member route, you need to passid
in the params to make it work, but you can do this to convert it to a collection routeHope that helps!
By default destroy method expects id, which should be pass with the link. For Ex. you are destroying session for logged in user, then you have to pass
id
orsession
of logged-in user, in this case, your link should be like this,<%= link_to "Sign out", session_path(user.id), method: :delete %>
or if your purpose is to just delete/clear session only then you need to change in route.If you want both types of link(In which we may pass ID or not), then you should try this route.
delete '/session(/:id)', to: 'sessions#destroy'
You need to pass the session resource to that route, like so:
Rails show and delete actions require a resource.
It is best to treat the routes to your sessions controller as a singular resource
routes.rb
Doc: http://guides.rubyonrails.org/routing.html#singular-resources
This will give you a route that you can use without ID's
DELETE /sessions sessions#destroy
You need to change the path, which in your case can be
/users/sign_out
orsessions/sign_out
and not/sessions
with aDELETE
method.Take a look at devise's session destroy action and the route.
So, you could use something like
Which will create path
/session/sign_out
which points tosessions#destroy
and you can call it in your views asdestroy_session_path
.