ruby-on-rails - 外键没有按预期工作

标签 ruby-on-rails postgresql ruby-on-rails-4

我知道这不是“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/

相关文章:

javascript - rails 4 : setting link destination in CoffeeScript function

javascript - jQuery 将事件类添加到导航,现在导航不起作用

ruby-on-rails - Rails 对象继承与belongs_to

ruby-on-rails - 在 ruby​​ on Rails 中按字母顺序对 json 数据进行排序

ruby-on-rails - ActiveRecord::StatementInvalid PG::UndefinedColumn: 错误

sql - 现在在 Postgresql 中 - 仅显示日期

ruby-on-rails - 如何将 ActiveSupport::TimeWithZone 实例格式化为指定格式

postgresql - 您可以逻辑地复制物理 Postgres 副本吗?

php - 这个 PostgreSQL 查询容易受到攻击吗?

ruby-on-rails - 从 rake 任务中运行工头