Accessing devise helper 'user_signed_in?' - ruby-on-rails

I'm unable to use 'user_signed_in?' in my application controller, and wondered if anyone knew how to fix it.
It's works fine in my views, but in my application controller i get
NoMethodError in PostsController#index
undefined method `user_signed_in?' for ApplicationController:Class
A lot of people had this problem on rail 3.0.3, but I'm using rails 2.3.8. The suggested fix was
to use devise_for :user in your routes.rb but that resulted in
Internal Server Error
undefined method `devise_for' for main:Object
Help would be greatly appreciated
Thanks

I use devise with 2.38
How about having
==> application_controller.rb <==
protected
def authorize
unless User.find_by_id(session[:user_id])
session[:original_uri] = request.request_uri
flash[:notice] = "Please Log In!"
redirect_to :controller => 'admin', :action => 'login'
end
end
end
then each controller, e.g. food_items:
class FoodItemsController < ApplicationController
before_filter :authorize, :except => [:index, :show] # For all methods except these...
# GET /food_items
slightly different approach. Might help.

Related

The action could not be found for a controller. But it's present

I have this sessions_controller.rb
class SessionsController < ApplicationController
skip_before_filter :login_joomla_user_or_redirect
def create
session[:joomla_user_id] = params[:joomla_user_id]
redirect_to root_path
end
def destroy
session[:joomla_user_id] = nil
redirect_to root_path
end
end
And a basic route
unless Rails.env.production?
get "login_as/:joomla_user_id" => "sessions#create", :as => :login
get "logout" => "sessions#destroy"
end
I cannot understand why when I try to login with the route the browser return to me:
The action 'create' could not be found for SessionsController
The action is there. Why?
I'm migrating this code from Rails 4.2 to Rails 6
Solution: replace max skip_before_filter that is deprecated with skip_before_action
I don't know why Rails doesn't give another error.
You should make your create and destroy methods to a postand delete.
See ruby on rails use "create" method in controller as GET not working for a similar question.
See https://guides.rubyonrails.org/routing.html for the official guide on routes.

Undefined method logged_in? Ruby on Rails

I can't make head or tail of this (but I'm probably being an idiot). I have a class ApplicationController that contains the following method:
def logged_in?
!current_user.nil?
end
if logged_in?
load_and_authorize_resource :unless => :devise_controller?, :except => :show
end
This gives me an error:
undefined method `logged_in?' for ApplicationController:Class
This method is clearly defined, how is it coming back as undefined?
Maybe the best place to declare it is in /helpers/application_helper.rb instead of application_controller.
Also, to verify if a user is signed in, Devise provides the following helper user_signed_in?.
Source: https://github.com/plataformatec/devise
I think you forgot to write:
helper_method :logged_in?
in ApplicationController.

Redirect to log in page if user is not authenticated with Devise

I'm using Devise with Ruby on Rails.
What is the recommended way to redirect unauthenticated users to the sessions#new page if they attempt to access a page that requires authentication?
Right now I get an error that says no route matches the one they attempt to access (leading to a 404 error in production).
Just simple add this method to application_controller.rb
protected
def authenticate_user!
if user_signed_in?
super
else
redirect_to login_path, :notice => 'if you want to add a notice'
## if you want render 404 page
## render :file => File.join(Rails.root, 'public/404'), :formats => [:html], :status => 404, :layout => false
end
end
And you can call this method on before_filter another controllers you want.
e.g :
class HomesController < ApplicationController
before_filter :authenticate_user!
## if you want spesific action for require authentication
## before_filter :authenticate_user!, :only => [:action1, :action2]
end
Don't forget add login_path into routes.rb
devise_scope :user do
match '/sign-in' => "devise/sessions#new", :as => :login
end
note : I always use this way when play with devise for my apps authentication.. (rails 3.2 and rails 4.0.1)
You can do just like GeekTol wrote, or just put
before_action :authenticate_user!
in your controller.
In this case, devise uses the default authenticate_user! method, that will redirect to the "user_session_path" and use the default flash message.
It's not necessary to rewrite authenticate_user! method, unless you want to customize it.
I thought you could just add:
before_action :authenticate_user!
to each controller that required the user to be logged in.
I'm a Rails beginner but I found this in my own searches and it works well in my application.
You should refer to Devise's own How To: How To: Redirect to a specific page when the user can not be authenticated.
Another alternative I can think of is creating a routing Constraint wrapping your protected routes. You'd better stick to Devise's way, but here is an example:
#On your routes.rb
constraints(Constraints::LoginRequired) do
get '/example'
end
#Somewhere like lib/constraints/login_required.rb
module Constraints
class LoginRequired
def self.matches?(request)
#some devise code that checks if the user is logged in
end
end
end
Add this code in your config/routes.rb devise_for :users and resources :users and you can generate devise in views.

uninitialized constant PurchasesController::UserMailer

I've generated a mailer for an Order confirmation. I'm getting a NameError at /purchases.
The error reads:
uninitialized constant PurchasesController::UserMailer
/controllers/purchases_controller.rb
class PurchasesController < InheritedResources::Base
before_filter :authenticate_admin_user!, :only => [:index, :edit, :update, :destroy]
def create
#purchase = Purchase.new(params[:purchase])
if #purchase.save
UserMailer.purchase_confirmation(#purchase).deliver
redirect_to "/thankyou"
else
render :action => "new"
end
I've been digging around and have found similar issues, but nothing as of yet to solve my problem. Any help?
It may be cause by two problems and the following is just an Idea...
1) You need to restart the rails server after you added the Mailer
(or)
Try to run in your production server and check it.
2) check the spell of UserMailer should be user_mailer.rb
(or)
Make sure that you are using UserMailer.
UserMailer.rb will break whereas user_mailer.rb is what is expected.
Let us know once its not solved the above two options

ActionController::RoutingError (undefined method `before_filter' for Class): Error

Basically I have a UsersInitializeController Class
class UsersInitializeController < ApplicationController
before_filter :authenticate_user!
def create
render true
end
end
authenticate_user! is found in the Application Controller
class ApplicationController < ActionController::Base
# protect_from_forgery
def authenticate_user!
#current_user = User.find_by_token params[:auth_token]
if !#current_user
#current_user = User.create :token => params[:auth_token]
end
end
end
When my application starts, it sends POST request to the UsersInitializeController. Since before_filter is set, it will thus call authenticate_user! first. However the error I got says before_filter is an undefined method.
From my knowledge, before_filter exist in ActionController, and since UsersInitializeContoller < ApplicationController < ActionController, I shouldn't be getting this error. Has anyone encounter this issue before ?
Exception Stack (as requested)
Started POST "/users_initialize.json" for 127.0.0.1 at 2012-03-06 00:32:50 -0800
ActionController::RoutingError (undefined method `before_filter' for UsersInitializeController:Class):
app/controllers/users_initialize_controller.rb:3:in `<class:UsersInitializeController>'
app/controllers/users_initialize_controller.rb:1:in `<top (required)>'
Routes.rb file (as requested)
MyApplication::Application.routes.draw do
resources :users_initialize
match 'info/required_client_version' => 'info#required_client_version'
end
### Problem Solved ###
Unused Devise Gem somehow causing the complication. Removed it and done.
add the before_filter within an "included do" block:
included do
before_filter :authenticate_user!
end
Update:
just noticed you solved it already. However I was having the same troubles and the solution above solved it in my case. So, I'll leave the comment here since it may help others
Not able to reproduce, the code you posted works fine on my Rails 3.2.2 app.
Probably there is something wrong with your source file (i.e. some extra hidden bytes somewhere).
You could try a step-by-step approach to solve this:
add a new UsersController and add resources :users to routes.rb
add an index action with the following code:
def index
render :text => "Hello there"
end
When you visit http://localhost:3000 you should see the text "Hello there"
Add the before_filter and verify that the filter is executed by adding e.g. logger.warn( 'In the Filter' ) to the beginning of the filter method

Resources