所以我有两个模型location
和menu
。每个location
都可以包含多个菜单,但每个menu
只有一个location
。
我对string
ID使用location
类型。但是,我无法rake db:migrate
为string
表上的外键生成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
那我在这里做错了什么?
答案 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