我知道这不是“Rails 方式”,但我正在尝试添加外键以在数据库级别实现引用完整性。我想创建一个名为 recipe_ingredients 的新表,它将有外键引用一个名为 recipes 的表和一个名为 ingredients 的表。这是我的迁移:
class CreateRecipeIngredients < ActiveRecord::Migration
def change
create_table :recipe_ingredients do |t|
t.references :recipe, null: false
t.references :ingredient, null: false
t.timestamps null: false
end
add_foreign_key :recipe_ingredients, :recipes
add_foreign_key :recipe_ingredients, :ingredients
end
end
迁移成功并生成以下内容:
Table "public.recipe_ingredients"
Column | Type | Modifiers | Storage | Stats target | Description
---------------+-----------------------------+-----------------------------------------------------------------+----------+--------------+-------------
id | integer | not null default nextval('recipe_ingredients_id_seq'::regclass) | plain | |
recipe_id | integer | | plain | |
ingredient_id | integer | | plain | |
measurement | character varying | not null | extended | |
created_at | timestamp without time zone | not null | plain | |
updated_at | timestamp without time zone | not null | plain | |
Indexes:
"recipe_ingredients_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"fk_rails_176a228c1e" FOREIGN KEY (recipe_id) REFERENCES recipes(id)
"fk_rails_209d9afca6" FOREIGN KEY (ingredient_id) REFERENCES ingredients(id)
问题是,当我尝试使用无效的 recipe_id 和/或 ingredient_id 创建新的 recipe_ingredient 时,它仍然认为它有效。我怎样才能让数据库在这些字段上强制执行参照完整性?我正在使用 postgresql 数据库。
最佳答案
调用 valid?
仅在模型上运行验证,直到您尝试将其实际插入数据库时,引用完整性检查才会启动。
在Rails 5 , 在你的模型中有 belongs_to
自动要求父存在。
class Child < ApplicationRecord
belongs_to :parent
end
您可以通过以下方式选择退出
belongs_to :parent, required: false
关于ruby-on-rails - 外键没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41703359/