所以我正在研究一个基于位置的 api,其中一个位置有很多用户,并且一个用户在特定时间属于某个位置。这意味着用户表将包含一个用作外键的 location_id 列。然而,这与我开发的大多数应用程序不同,例如,用户将拥有许多“产品”。所以,我在我的 locations_controller.rb 文件中有这个
class Api::V1::LocationsController < ApplicationController
before_action :authenticate_with_token!, only: [:create]
respond_to :json
def show
respond_with Location.find(params[:id])
end
def create
# @location = current_user.locations.build(location_params)
@location = Location.new(location_params)
current_user.location = @location
current_user.save
if @location.save
render json: @location, status: :created, location: [:api, :v1, @location]
else
render json: {errors: @location.errors}, status: :unprocessable_entity
end
end
private
def location_params
params.require(:location).permit(:latitude, :longitude, :address)
end
end
但我得到了错误
Started POST "/api/v1/locations" for 127.0.0.1 at 2016-12-20 10:05:50 +0100
Processing by Api::V1::LocationsController#create as JSON
Parameters: {"location"=>{"latitude"=>"2.23413", "longitude"=>"2.908019", "address"=>"Sims1 streets"}}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."auth_token" IS NULL LIMIT 1
Filter chain halted as :authenticate_with_token! rendered or redirected
Completed 401 Unauthorized in 5ms (Views: 0.2ms | ActiveRecord: 0.5ms)
我的问题是:我该如何解决这个问题?我到处搜索,但都无济于事。请帮忙
我的authenticable.rb 文件是
module Authenticable
# Devise methods overrides. This finds the user by auth_token and it's sent to the server
def current_user
@current_user ||= User.find_by(auth_token: request.headers["Authorization"])
end
def authenticate_with_token!
render json: { errors: "Not authenticated" }, status: :unauthorized unless user_signed_in?
end
def user_signed_in?
current_user.present?
end
end