ActiveRecord`instry_to`用于除整数之外的主键类型

时间:2018-05-01 19:51:02

标签: ruby-on-rails activerecord rake

所以我有两个模型locationmenu。每个location都可以包含多个菜单,但每个menu只有一个location

我对string ID使用location类型。但是,我无法rake db:migratestring表上的外键生成menu类型的正确模式。

模型:

class Location < ActiveRecord::Base
  self.primary_key = :id

  has_many :menus
end

class Menu < ActiveRecord::Base
  belongs_to :location
end

迁移:

class CreateLocations < ActiveRecord::Migration[5.1]
  def change
    create_table :locations, id: false do |t|
      t.string :id, primary_key: true

      t.timestamps
    end
  end
end

class CreateMenus < ActiveRecord::Migration[5.1]
  def change
    create_table :menus do |t|
      t.belongs_to :location
      # other stuff
    end
  end
end

导致此架构

ActiveRecord::Schema.define(version: 20180413142949) do
  create_table "locations", primary_key: "id", id: :string, force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
    create_table "menus", force: :cascade do |t|
    t.bigint "location_id"
    t.text "name", null: false
    # other stuff
    t.index ["location_id"], name: "index_menus_on_location_id"
  end
end

那我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

您似乎需要修改menus表的迁移。你尝试过这样的事吗?

t.references :locations, type: :string, index: true

或者:

class CreateMenus < ActiveRecord::Migration[5.1]
  def change
    create_table :menus
    add_reference(:menus, :location, type: :string, foreign_key: true)
  end
end