سؤال

I'm beginning with Rails for some days now. I'm trying to make a form application that requires the users to be logged in in every case.

So I made the user login Railcast : http://railscasts.com/episodes/250-authentication-from-scratch

Now, I need to make the login required in my other controllers, so the user can't access the whole application without being logged in. I tryed this method :

application_controller.rb

class ApplicationController < ActionController::Base

  protect_from_forgery with: :exception

  helper_method :current_user

  private

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  def logged_in
    return true if current_user 
  end 

  def login_required 
    if logged_in false
      redirect_to log_in_path and return false 
     end                                                                                                                    
  end 

end 

categories_controller.rb

class CategoriesController < ApplicationController
  before_filter :login_required
  def new

  def index
     @categories = Categorie.all
  end

It returns me this error :

ArgumentError in CategoriesController#index wrong number of arguments (1 for 0)

 Extracted source (around line #14):    
    def logged_in
        return true if current_user
    end 

Does my before_filter :login_required needs something else ? I don't really understand this error.

هل كانت مفيدة؟

المحلول

You defined a method named logged_in which take no arguments but you are calling it with 1 argument:

if logged_in(false)

You should be doing:

if logged_in

Your code should probably look like this:

def logged_in
  current_user 
end 

def login_required 
  return false if logged_in
  redirect_to log_in_path
end
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top