gpt4 book ai didi

ruby-on-rails - 未定义的方法 `authenticate_user! Devise/Rails 4 中的 Api::PostsController

转载 作者:行者123 更新时间:2023-12-04 17:19:00 24 4
gpt4 key购买 nike

我的项目中有以下路线:

  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

session Controller :
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

应用 Controller :
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

最后我的 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

但是当我尝试创建一个新帖子时,我收到以下错误:“未定义的方法 `authenticate_user!Api::PostsController”。如果我删除它,我会收到关于“current_user”方法的错误。有什么问题?我该如何解决?提前致谢!!!

最佳答案

由于 :api 中的嵌套设计,您会收到该错误您的 routes.rb 中的命名空间文件。因此,您应该通过以下方式对用户进行身份验证:

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

关于ruby-on-rails - 未定义的方法 `authenticate_user! Devise/Rails 4 中的 Api::PostsController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27164906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com