NoMethodError в AuthenticationController#create | омниаут + разработка

NoMethodError в AuthenticationController#create

неопределенный метод `user' для # /Authentication:0x00000105c7b1f8\

Я рву на себе волосы. Я скачал образец приложения с railscasts, и он работает. У меня есть что-то похожее на последнюю ошибку.

Я пытаюсь следить за railscasts, чтобы добавить это в свое приложение, которое в остальном работает/работало - http://railscasts.com/episodes/236-omniauth-part-2

Вроде в основном доходит - в таблице авторизаций есть запись..

Я не дошел до шага, когда страница запрашивает электронное письмо, потому что его нет.

Я уверен, что это супер просто - вот несколько фрагментов:

контроллер:

class AuthenticationsController < ApplicationController

  def create
    omniauth = request.env["omniauth.auth"]
    authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
    if authentication
      flash[:notice] = "Signed in successfully."
      sign_in_and_redirect(:user, authentication.user)
    elsif current_user
      current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
      flash[:notice] = "Authentication successful."
      redirect_to authentications_url
    else
      @user = User.new
      @user.apply_omniauth(omniauth)
      if @user.save
        flash[:notice] = "Signed in successfully."
        sign_in_and_redirect(:user, user)
      else
        session[:omniauth] = omniauth.except('extra')
        redirect_to new_user_registration_url
      end

    end
  end

end

разработать пользовательскую модель:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  has_many :authentications

  devise :database_authenticatable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  #attr_accessible :email, :password, :password_confirmation, :remember_me

  def apply_omniauth(omniauth)
    self.email = omniauth['user_info']['email'] if email.blank?
    authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
  end

  def password_required?
    (authentications.empty? || !password.blank?) && super
  end

end

некоторые из route.rb:

  resources :authentications
  match '/auth/:provider/callback' => 'authentications#create'

  get "search/show"

  #devise_for :users
  devise_for :users, :controllers => {:registrations => 'registrations'}

person Troy Anderson    schedule 15.05.2011    source источник


Ответы (1)


В sign_in_and_redirect(:user, user) должно быть @user. Не user.

person ujifgc    schedule 16.05.2011
comment
Это сработало! Я знал, что это просто.. но не так просто :) спасибо!! (У меня новые проблемы.. но я с ними разберусь) - person Troy Anderson; 17.05.2011
comment
... или наоборот, вы должны были использовать user в предыдущих трех строках, т.е. user = User.new; user.apply_omniauth(omniauth); if user.save ... Переменные экземпляра отличаются от локальных переменных - вы не можете их смешивать, кроме того, на самом деле нельзя, поскольку они также подразумевают другую цель. - person Michael De Silva; 20.06.2011