2014-11-27 11 views
8

मेरे परियोजना में निम्नलिखित मार्गों है:अपरिभाषित विधि `authenticate_user! एपीआई :: वसीयत में PostsController/रेल 4

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 

लेकिन जब मैं एक नई पोस्ट बनाने का प्रयास करें मैं निम्नलिखित त्रुटि मिलती है: "अपरिभाषित विधि` authenticate_user! Api :: PostController "। अगर मैं इसे हटा देता हूं, तो मुझे 'current_user' विधि के बारे में त्रुटि मिलती है। क्या समस्या है? मैं इसे कैसे ठीक कर सकता हूं? अग्रिम धन्यवाद !!!

+0

निकालने का प्रयास करें! –

उत्तर

3

मुझे devise का उपयोग कर एक ही समस्या थी। मुद्दा मेरे मामले में है कि मैं नहीं बल्कि उपयोगकर्ता की तुलना में एक अलग नाम के साथ अपने डाटाबेस नामित (i 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 

आशा की तरह था यह मदद करता है!

12

:api नेमस्पेक के भीतर घोंसले के निर्माण के कारण आपको यह त्रुटि मिलती है ई routes.rb फ़ाइल में। इसलिए, आपको निम्न तरीकों से उपयोगकर्ताओं को प्रमाणित करना चाहिए:

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

यह एक बहुत ही अजीब पैटर्न है! – mekdigital

संबंधित मुद्दे