简体   繁体   English

为什么我得到这个`ActiveRecord :: RecordNotFound。 (找不到'id')`我的Rails API中的POST请求出错?

[英]Why am I getting this `ActiveRecord::RecordNotFound. (Couldn't find 'id') ` error from POST requests in my Rails API?

Some context. 一些背景。 I am creating an API that is contacted by an external server. 我正在创建一个由外部服务器联系的API。 This external server contacts the API with POST requests to the endpoint /vehicles with a unique id number. 该外部服务器使用唯一的ID号向端点/vehicles发送POST请求来联系API。 The request body has the format { "id": “some_string_here” } . 请求主体的格式为{ "id": “some_string_here” } My API stores these in the db. 我的API将这些存储在db中。 After the vehicles have been created the external server then makes POST requests with the endpoint vehicles/:id/locations with the request body looking something like this { "lat": 10.0, "lng": 20.0, "at": "2019-09-01T12:00:00Z" } - adding lat lng coordinates and a time stamp to each vehicle periodically (to update the vehicle's location). 在创建车辆后,外部服务器将使用端点vehicles/:id/locations发出POST请求,请求主体看起来像这样{ "lat": 10.0, "lng": 20.0, "at": "2019-09-01T12:00:00Z" } -定期向每辆车添加经纬度坐标和时间戳(以更新车的位置)。

I have been able to set up my API with vehicles and locations controllers and when I start the external server the vehicles are stored successfully. 我已经能够使用vehicleslocations控制器设置我的API,并且当我启动外部服务器时,车辆已成功存储。 The problem I have is when the server then starts to send requests to add locations to each vehicle. 我的问题是服务器随后开始发送请求以将位置添加到每辆车时。 In the console I get the message: 在控制台中,我收到消息:

Processing by LocationsController#create as HTML

  Parameters: {"lat"=>52.44381, "lng"=>13.47686, "at"=>"2019-07-28T16:56:45.311Z", "vehicle_id"=>"d759fc35-b25c-4877-8e40-9b0104447b31", "location"=>{"lat"=>52.44381, "lng"=>13.47686, "at"=>"2019-07-28T16:56:45.311Z"}}
ActiveRecord::RecordNotFound (Couldn't find Vehicle with 'id'=d6880741-ae7f-4741-aa04-950b0a1e2d3b):
Can't verify CSRF token authenticity.

app/controllers/locations_controller.rb:9:in `create'
  Vehicle Load (38.2ms)  SELECT  "vehicles".* FROM "vehicles" WHERE "vehicles"."id" = $1 LIMIT $2  [["id", 0], ["LIMIT", 1]]
  ↳ app/controllers/locations_controller.rb:9
Completed 404 Not Found in 50ms (ActiveRecord: 38.2ms)

ActiveRecord::RecordNotFound (Couldn't find Vehicle with 'id'=d759fc35-b25c-4877-8e40-9b0104447b31):

The problem might have something to do with the fact that the requests to store a vehicle have id as the key in the body (the same name as the default primary key column name). 该问题可能与以下事实有关:存储车辆的请求具有id作为主体中的键(与默认主键列名称相同的名称)。 This meant that I had to create a new column for the vehicle id that the server is passing and then add this code in my controller to change the params hash: 这意味着我必须为服务器通过的车辆ID创建一个新列,然后在控制器中添加以下代码以更改params哈希:

def vehicle_params
  params[:vehicle][:unique_id] = params[:vehicle].delete(:id)
end 

This meant that vehicles were stored correctly, however it may (or may not) be the reason why I am getting the error message described above. 这意味着车辆已正确存储,但是这可能是(也可能不是)我收到上述错误消息的原因。 Any ideas how I can fix this? 有什么想法我可以解决这个问题吗? My relevant code is below. 我的相关代码如下。

vehicles_controller.rb Vehicles_controller.rb

class VehiclesController < ApplicationController
...
  def create
    @vehicle = Vehicle.new(vehicle_params)

    respond_to do |format|
      if @vehicle.save
        format.json { render status: :created, location: @vehicle }
      else
        format.json { render json: @vehicle.errors, status: :unprocessable_entity }
      end
    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 locations_controller.rb

class LocationsController < ApplicationController
...
  def create
    @vehicle = Vehicle.find(params[:vehicle_id])
    @location = @vehicle.locations.new(location_params)


    respond_to do |format|
      if @location.save
        format.json { render :show, status: :created, location: @vehicle }
      else
        format.json { render json: @location.errors, status: :unprocessable_entity }
      end
    end
  end

  private

    def location_params
      params.require(:location).permit(:lat, :lng, :at, :vehicle_id)
    end
end

routes.rb routes.rb

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

schema.rb schema.rb

ActiveRecord::Schema.define(version: 2019_07_27_224818) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  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

Any help would be greatly appreciated! 任何帮助将不胜感激!

It looks like the string d6880741-ae7f- .... is supposed to correspond to the unique_id column on vehicles. 字符串d6880741-ae7f- ....应该与车辆上的unique_id列相对应。 In which case you would use 在这种情况下,您将使用

@vehicle = Vehicle.find_by!(unique_id: params[:vehicle_id])

The id column is an int, and params[:vehicle_id] is a string ... thus Vehicle.find(params[:vehicle_id]) would always raise a "not found" error, which is the behavior you're seeing. id列是一个int,而params[:vehicle_id]是一个字符串...因此Vehicle.find(params[:vehicle_id])总是会引发“找不到”错误,这就是您所看到的行为。

Note that find and find_by! 注意findfind_by! will raise an error if the record is not found. 如果找不到记录,将引发错误。 If you don't want to have this happen, you can use find_by (without the exclamation point) - it just returns nil if the record is not found. 如果您不希望发生这种情况,则可以使用find_by (不带感叹号)-如果未找到该记录,它只会返回nil。 But you will have to change your code to account for the possibility that @vehicle is nil. 但是您必须更改代码以解决@vehicle为零的可能性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在编辑书籍列表的 Rails 应用程序中出现错误 ActiveRecord::RecordNotFound in BooksController#edit 找不到 id=id 的书籍 - Getting error in my rails application of editing a list of books ActiveRecord::RecordNotFound in BooksController#edit Couldn't find Book with id=id Rails 4错误:ActiveRecord :: RecordNotFound找不到&#39;id&#39;= - Rails 4 Error: ActiveRecord::RecordNotFound Couldn't find 'id'= Rails 4错误:ActiveRecord :: RecordNotFound找不到&#39;id&#39; - Rails 4 Error: ActiveRecord::RecordNotFound Couldn't find 'id' Rails 4错误:ActiveRecord :: RecordNotFound找不到id = - Rails 4 Error: ActiveRecord::RecordNotFound Couldn't find id= Rails 4错误:ActiveRecord :: RecordNotFound /找不到&#39;id&#39;= - Rails 4 Error: ActiveRecord::RecordNotFound / Couldn't find 'id'= 我在/ posts / post / edit中收到以下错误ActiveRecord :: RecordNotFound找不到带有&#39;id&#39;= post的帖子 - I get the following error ActiveRecord::RecordNotFound at /posts/post/edit Couldn't find Post with 'id'=post ActiveRecord :: RecordNotFound-在Rails中找不到ID =的用户 - ActiveRecord::RecordNotFound - Couldn't find User with id= in Rails Rails-ActiveRecord :: RecordNotFound(找不到带有&#39;id&#39;= 27的评论): - Rails - ActiveRecord::RecordNotFound (Couldn't find Comment with 'id'=27): ActiveRecord::RecordNotFound in CommentsController#create,找不到带有“id”= 的帖子 - ActiveRecord::RecordNotFound in CommentsController#create, Couldn't find Post with 'id'= ActiveRecord::RecordNotFound in PostsController#show, 找不到带有 &#39;id&#39;=# 的帖子 - ActiveRecord::RecordNotFound in PostsController#show, Couldn't find Post with 'id'=#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM