0
votes

I've set up a simple web-application with rails 4 and am struggling with a find_or_create_by. Despite the entry being in my SQLite-database when executing the query manually it doesn't return anything.

This is the code in my controller:

login_as User.find_or_create_by(
    :user_id  => 20827
)

This is my application-controller:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_filter :login_from_session

  def logged_in?
    !!current_user
  end

  def current_user
    @current_user
  end

  def login_as(user)
    raise user
    @current_user = user
    session[:current_user_id] = user.try(:id)
  end

  def login_from_session
    @current_user = User.find_by_id(session[:current_user_id])
  end
end

This is the output on the webserver:

User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1

User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 20827 LIMIT 1

Completed 500 Internal Server Error in 7ms

TypeError (exception class/object expected):

app/controllers/application_controller.rb:18:in `raise'

app/controllers/application_controller.rb:18:in `login_as'

The raise(user) on login_as() doesn't return an object.

What am I doing wrong?

1
There should be some error.You checked in console?Pavan
There is just a TypeError telling me that the "User" object I tried to retrieve from the database doesn't existHedge
No.It is telling that either an object(instance variable) or exception class is expected for raise. Try using raise @current_user.inspectPavan
It worked, thanks a lot.Hedge

1 Answers

1
votes

TypeError (exception class/object expected):

app/controllers/application_controller.rb:18:in `raise'

app/controllers/application_controller.rb:18:in `login_as'

Try using raise @current_user.inspect instead

def login_as(user)
    raise @current_user.inspect
    @current_user = user
    session[:current_user_id] = user.try(:id)
  end