Search code examples
ruby-on-railsnginxunicornbcrypt

Rails 4 NoMethodError validate (bcrypt)


I am trying to launch my Rails 4 App in production (it is just a simple blog with a signin form for users from the database to be able to login and CRUD)

I am running nginx with unicorn and bcrypt for user authentication with has_secure_password on the User model. When I try to signin a user my production.log shows:

NoMethodError (undefined method `authenticate' for nil:NilClass):
app/controllers/sessions_controller.rb:9:in `create'

in my Sessions controller this block is what is calling the authenticate method:

user = User.find_by_email(params[:session][:email])
if user && user.authenticate(params[:session][:password])
    sign_in user
    redirect_to root_path
else
    flash.now[:warning] = "Invalid User/Password combination"
    render 'new'
end

unless I change the else statement to soemthing else I get the "Invalid User/Password combination" error message and it renders /sessions

What's really strange is that when I run User.find_by_email("user's email").authenticate("user's password") in rails console I get the user returned to me.

I am completely stumped as to why my user authentication works in development mode but not production!

Here is the github repo of a sample app experiencing the same problem: https://github.com/sentrathis96/debug_app


Solution

  • The problem I was having was creating a user in the development database, not production. So on the production VPS I had to run RAILS_ENV=production rails c to create my user so there'd be a user record to login with.

    Make sure to create the necessary records in the necessary environments if you run into something similar!