0

I have a PagesController that handles all the static pages of my application. It has a method called join_session which renders the view pages/page_a.html.erb. This works.

My problem: I'm writing a method that renders the last viewed page when the user logs back in (using the Devise hook after_database_authentication in the User model).

Can I call the PagesController join_session method from the User model?


[I couldn't figure out how to do that, so I tried a hacky workaround: writing and calling a class method in PagesController, and rendering the view there, but since the name of the new method did not match the name of the controller method in the route, the variables in the view could not be resolved.]

My route:

get 'pages/page_a', to: 'pages#join_session'

Help would be much appreciated! :)

megahra
  • 295
  • 2
  • 19
  • Can I ask why you want to call a controller method from models? In vast majority of cases, you'd call model methods in controller, but not the other way around. – Jason Kim Nov 10 '17 at 23:22
  • @Jason : I'm using the Devise hook `after_database_authentication` to execute code after a user successfully logs in that will determine which static page was last shown to them and then try to render it. As far as I've gathered from the thread I linked above I need to overwrite this method in the `User` model (I have tried placing it in a controller - it did not work). – megahra Nov 10 '17 at 23:47

1 Answers1

0

I think there is a pretty standard way to do this in your ApplicationController, you should check out this guide by Devise.

https://github.com/plataformatec/devise/wiki/How-To:-redirect-to-a-specific-page-on-successful-sign-in

I hope this helps. If you have any questions let me know.

aks
  • 8,796
  • 11
  • 50
  • 78
  • 1
    Yes, thank you! Unfortunately, there is a problem: There are cases for my app, where a user logs in and isn't supposed to be redirected anywhere (instead I send them some content with ActionCable and update the DOM to display it). Using `after_sign_in_path_for` [I got an error](http://stackoverflow.com/questions/47168969/nomethoderror-in-devisesessionscontrollercreate-when-using-after-sign-in-pat) for all the cases where I didn't want to redirect. So finally I switched over to using `after_database_authentication` and now I can't get the cases with redirects to work D: cycle of doom... – megahra Nov 12 '17 at 00:08
  • It happens all the time, glad you explored few things. :) – aks Nov 12 '17 at 04:15