外键上的模型关联不是整数

时间:2016-08-22 13:35:15

标签: ruby-on-rails

我正在使用rails构建API,我有2个模型: has_one :: document

的车辆
class CreateVehicles < ActiveRecord::Migration
   def change
      create_table :vehicles do |t|
          t.string :uuid, limit: 36, null: false, index: true
          t.string :license_plate_id
          t.integer :mileage
          t.string :mileage_unit, default: 'km'
          t.belongs_to :user, index: true

          t.timestamps null: false 
       end
    end
end

Vehicle.rb

class Vehicle < ActiveRecord::Base
  audited

  include UuidConcern

  belongs_to :user

  serialize :response, JSON

  has_one :vehicle_document, dependent: :destroy
end

VehicleDocument belongs_to :: Vehicle

class CreateVehicleDocuments < ActiveRecord::Migration
   def change
      create_table :vehicle_documents do |t|
         t.string :uuid, limit: 36, null: false, index: true
         t.integer :status, default: 0
         t.attachment :file
         t.belongs_to :vehicle, index: true
         t.timestamps null: false
      end
      add_index :vehicle_documents, :status
   end
 end

vehicle_document.rb:

class VehicleDocument < ActiveRecord::Base
  audited

  include UuidConcern
  self.primary_key = :uuid

  belongs_to :vehicle
end
问题是我想使用uuid作为车辆ID。我不想在我的API之外公开真实的ID。 我该怎么办? 我是否必须在迁移文件中执行此操作?模特? 我不应该这样做吗? 非常感谢

1 个答案:

答案 0 :(得分:1)

看起来你的问题是数据建模而不是Rails。实际上,如果你想知道如何在Rails中做一些事情,你必须先知道你想要做什么!

所以你有表格vehicles和简称documentsdocuments的每条记录都跟踪(属于)vehicle。您有两种选择:使用vanilla ID,因此常规关联将使用自动增量ID进行跟踪,您不一定需要通过API公开。

或者,您可以使用uuid直接跟踪数据库中的关联,但documents上的列必须能够容纳它。毕竟,你不能将uuid放在整数列中。因此,您可以将documents.vehicle_id设为uuid类型,而不是serial / integer。 (取决于您的数据库系统)

查看t.references的文档,导致connection.add_reference,提供了有关可用选项的提示:

  

:type
     参考列类型。默认为:integer

实际上,只需要更改列定义以反映正确的数据类型。

相关问题