undefined方法`authenticate_user! Devise / Rails 4中的Api :: PostsController
我的项目中有以下路线:
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
最后我的邮政控制器:
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
但是当我尝试创建一个新post时,我收到以下错误:“undefined method`certateate_user!Api :: PostsController”。 如果我删除它,我会收到有关’current_user’方法的错误。 有什么麻烦? 我该如何解决? 提前致谢!!!
由于routes.rb
文件中的:api
命名空间中的嵌套设计,您会收到该错误。 因此,您应该通过以下方式validation用户:
class Api::PostsController < ApplicationController before_action :authenticate_api_user!, only: [ :create ] end
我使用设计时遇到了类似的问题。 问题是我用不同的名称命名我的数据库而不是用户(我命名为xuser)。 在我的情况下,我所要做的就是重命名控制器中的变量。 像这样的东西
before_action :authenticate_xuser!, only: [ :create ] def create current_xuser.posts.create!(post_params) end private def post_params params.require(:post).permit(:title, :content) end
希望能帮助到你!
- rails 3 + devise:如果注册表有错误,如何防止其他字段中的数据被删除?
- 用于Rails应用程序的R统计包Gem
- 缺少主机链接! 请提供:host参数或设置default_url_options (ActionView :: Template :: Error)
- Rails路由:name而不是:id url参数
- Rails中脚手架和模型之间的区别
- Rails Concerns,Scopes,Devise,User.current和current_user
- 如何从Rails应用程序中完全删除Yarn?
- Rails – 单表inheritance与否是申请人/员工关系
- warden回调应该放在rails应用程序中的哪个位置?