undefined method `authenticate_user! Api::PostsController in Devise / Rails 4 -
there following routes in project:
root 'home#index' namespace :api, defaults: { format: :json } devise_for :users, controllers: { sessions: "api/sessions" } resources :posts end
user model:
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
application controller:
class applicationcontroller < actioncontroller::base # prevent csrf attacks raising exception. # apis, may want use :null_session instead. #protect_from_forgery with: :exception end
at last 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
but when try create new post following error: "undefined method `authenticate_user! api::postscontroller". if delete it, error 'current_user' method. what's trouble? how can fix it? in advance!!!
you error because of nesting devise within :api
namespace in routes.rb
file. therefore, should authenticate users in following way:
class api::postscontroller < applicationcontroller before_action :authenticate_api_user!, only: [ :create ] end
Comments
Post a Comment