Klortho
Klortho

Reputation: 823

In Ruby on Rails, how do I pass control to an action in another controller?

I have found several references that describe the difference between render and redirect_to, but none that let me know how to do exactly what I want, which is to pass control directly (within this same request, so no redirect_to) to an action in another controller.

Basically, I want to fix a bug in the sample code that I'm using for handling logins and sessions. If I log in, but then later do a rake db:seed, it changes all of the IDs for users, and my login session becomes invalid. This causes a nasty exception to be thrown when I try to get the current user, with this:

@current_user ||= Reviewer.find(session[:reviewer_id])

So to fix it, I want to put a check in my "before_filter", ensure_login. Something like this (but this does not work):

unless Reviewer.where(id: session[:reviewer_id]).first
  render :action => 'sessions/destroy'
end

This attempts to render the template associated with sessions/destroy, but of course there isn't one. I think the solution must be something very simple, but I'm stuck.

Upvotes: 3

Views: 454

Answers (2)

RahulOnRails
RahulOnRails

Reputation: 6542

Use of redirect_to

For example

redirect_to '/SignOut'

In routes like

  resources :user_sessions
  match '/SignOut', to: 'user_sessions#destroy'

Upvotes: 0

Mori
Mori

Reputation: 27779

The solution isn't to instantiate another controller and call an action on that (poor organization and too much overhead), but to put the code you want to call in some commonly accessible location, like a helper or lib file, e.g.:

# in a controller
unless ...
  render_session_destroy
end

# in a relevant helper
def render_session_destroy
   ...
end

Then render_session_destroy can also be called from its original controller.

Upvotes: 6

Related Questions