Я создал приложение для демонстрации подлинности в рельсах, используя Devise gem. Я создал контроллер сеанса для входа в систему. Но когда я посылаю запрос localhost:3000/api/v1/sessions/
с помощью почтальона контроллера сеанса я получаю следующее сообщение об ошибке:Rails: Невозможно sign_in пользователя с помощью Devise
"Could not find a valid mapping for #<User id: 2, email: "[email protected]", encrypted_password: "$2a$10$J5lCfQzWsxvjsXe.3EXfZ.ST9nztLLW8fhqYgXNtJP1...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2016-03-26 03:59:22", updated_at: "2016-03-26 03:59:22", auth_token: "_D3GU1TftgP7YHNcRftN">"
Вот моя модель users.rb
class User < ActiveRecord::Base
before_create :generate_authentication_token!
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :auth_token, uniqueness: true
def generate_authentication_token!
begin
self.auth_token = Devise.friendly_token
end while self.class.exists?(auth_token: auth_token)
end
end
Вот мои сессии контроллер
class Api::V1::SessionsController < ApplicationController
def create
user_password = params[:session][:password]
user_email = params[:session][:email]
puts user_password
puts user_email
user = user_email.present? && User.find_by(email: user_email)
if user.valid_password? user_password
sign_in user, store: false
user.generate_authentication_token!
user.save
render json: user, status: 200
else
render json: { errors: "Invalid email or password" }, status: 422
end
end
end
И мой routes.rb файл:
Rails.application.routes.draw do
# API routes path
namespace :api, defaults: { format: :json } do
namespace :v1 do
resources :users, only: [:show, :create, :update]
resources :sessions, only:[:create, :destroy]
end
end
end
Application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module DemoApi
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
DeviseController.respond_to :html, :json
end
end
Я был бы очень признателен, если кто-то может сказать мне, где я буду неправильно. Благодаря
«DeviseController.respond_to: html:: json» добавьте эту строку в свой 'config/application.rb' –
После добавления выше строки и перезапуска сервера я получаю следующую ошибку в моей консоли «/ home/paras/rails/demoApi/config/application.rb: 26: в ' ': uninitialized constant DemoApi :: Application :: DeviseController (NameError)" –
Paras