【发布时间】:2014-11-27 07:05:44
【问题描述】:
我的项目中有以下路线:
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
最后是我的 Post 控制器:
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”方法的错误。有什么问题?我该如何解决?先谢谢了!!!
【问题讨论】:
标签: ruby-on-rails devise