未定义的方法`authenticate_user! Api :: PostsController in Devise / Rails 4 [英] undefined method `authenticate_user! Api::PostsController in Devise / Rails 4

查看:285
本文介绍了未定义的方法`authenticate_user! Api :: PostsController in Devise / Rails 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有以下路线:

There is the following routes in my project:

  root 'home#index'

  namespace :api, defaults: { format: :json } do
    devise_for :users, controllers: { sessions: "api/sessions" }
    resources :posts
  end

用户模型:

class User < ActiveRecord::Base
    has_many :posts,        dependent: :destroy
    has_many :comments, dependent: :destroy

    validates :name, presence: true

    devise :database_authenticatable, :rememberable
end

会话控制器:

class Api::SessionsController < Devise::SessionsController
  def create
    @user = User.find_for_database_authentication(email: params[:user][:email])
    if @user && @user.valid_password?(params[:user][:password])
        sign_in(@user)
    else
        warden.custom_failure!
      @errors = [ 'Invalid email or password' ]
        render 'api/shared/errors', status: :unauthorized
    end
    end
end

应用程序控制器:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  #protect_from_forgery with: :exception
end

最后我的帖子控制器:

At last my Post controller:

class Api::PostsController < ApplicationController
    before_action :authenticate_user!, only: [ :create ]

    def create
      current_user.posts.create!(post_params)
    end

    private

        def post_params
            params.require(:post).permit(:title, :content)
        end
end

但是当我尝试创建一个新的帖子我得到以下错误:undefined方法`authenticate_user!Api :: PostsController。如果我删除它,我收到有关'current_user'方法的错误。有什么麻烦我该怎么解决?感谢提前!!!

But when I try to create a new Post I get the following error: "undefined method `authenticate_user! Api::PostsController". If I delete it, I get the error about 'current_user' method. What's the trouble? How can I fix it? Thanks in advance!!!

推荐答案

由于嵌套设计在中:api 命名空间在您的 routes.rb 文件中。因此,您应该通过以下方式验证用户:

You get that error because of nesting devise within the :api namespace in your routes.rb file. Therefore, you should authenticate users in the following way:

class Api::PostsController < ApplicationController
    before_action :authenticate_api_user!, only: [ :create ]
end

这篇关于未定义的方法`authenticate_user! Api :: PostsController in Devise / Rails 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆