我如何使我的Rails API索引动作仅显示我有嵌套路线时的某个ID的实例



我有一个带有嵌套路线的导轨API,该路线应仅显示带有端点/vehicles/:vehicle_id/locations特定ID的车辆位置,但是端点为我提供了所有车辆的所有位置。有什么想法我做错了什么?这是我的代码。

routes.rb

Rails.application.routes.draw do
  resources :vehicles do
    resources :locations
  end
end

schema.rb

ActiveRecord::Schema.define(version: 2019_07_27_224818) do
  create_table "locations", force: :cascade do |t|
    t.float "lat"
    t.float "lng"
    t.datetime "at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "vehicle_id"
  end
  create_table "vehicles", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "unique_id"
  end
end

控制器/vericles_controller.rb

class VehiclesController < ApplicationController
   skip_before_action :verify_authenticity_token
  def index
    @vehicles = Vehicle.all
    render json: @vehicles
  end
  def create
    @vehicle = Vehicle.new(vehicle_params)
    respond_to do |format|
      if @vehicle.save
        format.html 
      else
        format.html 
      end
    end
  end
  def destroy
    @vehicle.destroy
    respond_to do |format|
      format.html
    end
  end
  private
    def vehicle_params
      # swap id column value with unique_id to avoid conflict with primary key
      params[:vehicle][:unique_id] = params[:vehicle].delete(:id)
      params.require(:vehicle).permit(:unique_id)
    end
end

locations_controller.rb

class LocationsController < ApplicationController
  skip_before_action :verify_authenticity_token
  def index
    @locations = Location.all.order("vehicle_id")
    render json: @locations
  end
  def create
    @vehicle = Vehicle.find_by!(unique_id: params[:vehicle_id])
    @location = @vehicle.locations.new(location_params)    
    respond_to do |format|
      if @location.save
        format.html 
      else
        format.html 
      end
    end
  end
  private
    def location_params
      params.require(:location).permit(:lat, :lng, :at, :vehicle_id)
    end
end

型号/车辆.rb

class Vehicle < ApplicationRecord
  has_many :locations
end

型号/位置.rb

class Location < ApplicationRecord
  belongs_to :vehicle
end

在位置controller的索引方法中,您仅获取所有位置而不是给定车辆的位置。

更改下面的位置controller索引方法,

def index
  @locations = Vehicle.find(params[:vehicle_id]).locations
  render json: @locations
end

我有一个带有嵌套路线的导轨API,该路线应仅显示带有端点/车辆/:车辆_ID/位置的特定ID的车辆位置,但是端点为我提供了所有车辆的所有位置。有什么想法我做错了什么?

您的许可控制器的索引操作正在显示所有位置,因为这正是您写的要做的:

def index 
  @locations = Location.all.order("vehicle_id") 
  render json: @locations 
end

为什么期望它做除了您写的事情以外的其他事情?

而是尝试:

def index 
  @vehicle = Vehicle.find(params[:vehicle_id])
  @locations = @vehicle.locations
  render json: @locations 
end

或仅:

def index 
  @vehicle = Vehicle.find(params[:vehicle_id])
  render json: @vehicle.locations 
end

最新更新