Undefined method to "authenticate" in ruby ​​on rails?

I am new to the Ruby on Rails application, I have already created CRUD, but I am still equipped with Loginand functions Logout.

This is my Session_controller:

def new
end

def create
  user = User.find_by(email: params[:session][:email].downcase)
  if user && user.authenticate(params[:session][:passkey])
    # Log the user in and redirect to the user show page.
  else
    # Create an error message.
  flash[:danger] = 'Invalid email/password combination' # Not quite right!
    render 'new'
  end
end

def destroy
end

It's my opinion: new.html.erb

<%= form_for(:session, url: login_path) do |f| %>

    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control' %>

    <%= f.label :passkey%>
    <%= f.password_field :passkey, class: 'form-control' %>

    <%= f.submit "Log in", class: "btn btn-primary" %>
<% end %>

This is my model:

class User< ActiveRecord::Base
  validates :first_name, :presence => true, :length => { :in => 3..20 }
  validates :last_name, :presence => true, :length => { :in => 3..20 }
  validates :email, :presence => true, :uniqueness => true, format: { with: /\A[^@\s]+@([^@.\s]+\.)+[^@.\s]+\z/ }
  validates :passkey, :confirmation => true, :length => {:in => 6..20}
end

When I click the login button, showing this error:

NoMethodError in SessionController # create undefined `authenticate 'method for #User:0x0000000d5c65e0>

How can I fix this error?

I use ruby 1.9.7 Rails 4.2.5andmysql2

That would help me a lot, please.

+4
source share
4 answers

Just add

has_secure_password

to your user model. Make sure you add

gem 'bcrypt-ruby'

into your gemfile.

"password_digest" ​​ .

. Rails , , #authenticate !

: github - Rails Project @Github Rails. user.rb, gemfile user_controller.rb.

+1

Ruby on rails application

, , Devise .

, Devise .

-

, ; warden sessions registrations.

, .

, , . , , - , , .

, , Devise, , ...


Devise, :

#Gemfile
gem 'devise', '~> 3.5', '>= 3.5.3'

$ rails generate devise:install
$ rails generate devise User
$ rake  db:migrate

controllers, routes warden strategies Devise; Model .

devise helpers :

#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
   before_action :authenticate_user! #-> user has to "login" to access app
end

current_user, user_signed_in? :

#app/views/layouts/application.html.erb
<%= render partial "nav" if user_signed_in? %>

, . , , .


, ,

undefined `authenticate '

, authenticate User. :

#app/models/user.rb
class User < ActiveRecord::Base
   def authenticate
      # do something
   end
end 

, Warden authenticate!

Warden; , . , warden env["warden"], , - :

#app/models/user.rb
class User < ActiveRecord::Base
   def authenticate
     env["warden"].authenticate! ....
   end
end
+2
+1

, has_secure_password. valid_password?.

0

Source: https://habr.com/ru/post/1622189/


All Articles