2010-10-20 3 views
0

Im new to Rails, и решил начать с Rails3. После того, как много поисковых запросов удалось получить немного работы Authlogic. Я могу зарегистрировать пользователя, войдите в систему & logout.Authlogic + Rails3 - undefined method `Login 'for nil: NilClass

Теперь я хотел бы добавить дополнительные функции, получить больше от работы authlogic. Я использую Railscast EP 160 в качестве ссылки.

Часть коды найдено на ошибках броска учебника: Например:

<!-- layouts/_topbar.erb --> 
<%= link_to "Login", login_path %> 

и я получаю следующее сообщение об ошибке:

undefined local variable or method `login_path' for #<#<Class:0x0000000311e8f8>:0x0000000310af38> 

Чтобы преодолеть это, ив просто использовал строку. то есть <% = link_to "Login", "/ UserSessions/new"%>

Теперь кажется, что я зашел в тупик. Когда я пытаюсь вывести текущего пользователя с помощью:

<%= @user.Login %> 

Я получаю сообщение об ошибке, которое я не могу обойти. Не могли бы вы мне помочь? Спасибо :) Ниже приведено сообщение об ошибке и код.

undefined method `Login' for nil:NilClass 

Полный Трассировка Читает [усеченные]

activesupport (3.0.0) lib/active_support/whiny_nil.rb:48:in `method_missing' 
app/views/layouts/_topbar.erb:16:in `_app_views_layouts__topbar_erb__4536428193941102933_40950340__3781575178692065315' 
actionpack (3.0.0) lib/action_view/template.rb:135:in `block in render' 
activesupport (3.0.0) lib/active_support/notifications.rb:54:in `instrument' 
actionpack (3.0.0) lib/action_view/template.rb:127:in `render' 
actionpack (3.0.0) lib/action_view/render/partials.rb:294:in `render_partial' 
actionpack (3.0.0) lib/action_view/render/partials.rb:223:in `block in render' 
activesupport (3.0.0) lib/active_support/notifications.rb:52:in `block in instrument' 
activesupport (3.0.0) lib/active_support/notifications/instrumenter.rb:21:in `instrument' 

параметров запроса: Нет

Мой Gemfile читает:

gem "authlogic", :git => "git://github.com/odorcicd/authlogic.git", :branch => "rails3" 

конфигурации/routes.rb:

resources :users 
    resources :user_sessions 
    resources :ibe 
    match ':controller(/:action(/:id(.:format)))' 

контроллеры/application_controller.rb: [часть, которая получает текущий пользователь .. также взятый из Интернета примеры]

def current_user_session 
    return @current_user_session if defined?(@current_user_session) 
    @current_user_session = UserSession.find 
    end 

    def current_user 
    return @current_user if defined?(@current_user) 
    @current_user = current_user_session && current_user_session.record 
    end 

модели/user_session.rb:

class UserSession < Authlogic::Session::Base 
include ActiveModel::Conversion 
    def persisted? 
    false 
    end 
    def to_key 
    new_record? ? nil : [ self.send(self.class.primary_key) ] 
    end 
end 

модели/пользователя. гь:

class User < ActiveRecord::Base 
    acts_as_authentic 
end 

контроллеры/users_controller.rb:

class UsersController < ApplicationController 
    before_filter :require_no_user, :only => [:new, :create] 
    before_filter :require_user, :only => [:show, :edit, :update] 

    def new 
    @user = User.new 
    end 

    def create 
    @user = User.new(params[:user]) 
    if @user.save 
     flash[:notice] = "Account registered!" 
     redirect_back_or_default account_url 
    else 
     render :action => :new 
    end 
    end 

    def show 
    @user = @current_user 

    end 

    def edit 
    @user = @current_user 

    end 

    def update 
    @user = @current_user # makes our views "cleaner" and more consistent 
    if @user.update_attributes(params[:user]) 
     flash[:notice] = "Account updated!" 
     redirect_to account_url 
    else 
     render :action => :edit 
    end 
    end 


end 

Хорошо, я решил переключиться на Devise .. кажется, работает из коробки с рельсами 3 .. yaay!

ответ

0

Пользователь не зарегистрирован, поэтому @user - это нуль. Поместите некоторую логику, как вы видите в примере приложения Rails3.

http://github.com/trevmex/authlogic_rails3_example/blob/master/app/views/layouts/application.html.erb

Примечание Я использую эту ветку для authlogic для rails3, хотя я не уверен, если это лучше или хуже, чем основная ветвь.

http://github.com/odorcicd/authlogic/tree/rails3

отметить Также я попытался rails3 с railscast 160, но это уже устаревшее. У меня было больше удачи, используя railscast только для базовой ориентации, а затем придерживаясь примера приложения из trevmex на github выше для фактической реализации.

+0

Спасибо, Питер! Мне жаль, что я не застрял немного дольше, чтобы увидеть ваш ответ. Но я просто сдался на authlogic и пошел с изобретением. Кажется хорошим до сих пор. –

Смежные вопросы