Có các tuyến đường sau đây trong dự án của tôi:phương thức chưa xác định `authenticate_user! Api :: PostsController trong lập mưu/Rails 4
root 'home#index'
namespace :api, defaults: { format: :json } do
devise_for :users, controllers: { sessions: "api/sessions" }
resources :posts
end
model User:
class User < ActiveRecord::Base
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
validates :name, presence: true
devise :database_authenticatable, :rememberable
end
phiên điều khiển:
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
ứng dụng điều khiển:
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
Cuối cùng điều khiển bài viết của tôi:
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
Nhưng khi tôi cố gắng tạo ra một bài viết mới, tôi nhận được lỗi sau: "Phương pháp xác định 'authenticate_user! Api :: PostsController ". Nếu tôi xóa nó, tôi nhận được lỗi về phương pháp 'current_user'. Có gì rắc rối? Làm thế nào tôi có thể sửa chữa nó? Cảm ơn trước !!!
Hãy thử xóa! –