【发布时间】:2017-09-26 01:17:59
【问题描述】:
我使用的是 Rails 5.1.3 版。
Rails 是否有办法验证外键值是否存在于可选关系中?
我有下一个模型:
class Post < ApplicationRecord
belongs_to :category, optional: true
validates :category, presence: true, allow_nil: true
end
这是迁移:
class CreatePosts < ActiveRecord::Migration[5.1]
def change
create_table :posts do |t|
t.string :name, limit: 100
t.references :category, foreign_key: true, null: true
t.timestamps
end
end
end
这些是案例:
# Case 1
p1 = Post.new({})
p1.save #Working as I expected ... record Inserted
# Case 2
p2 = Post.new({category_id: 3}) # A category with id 3 exists
p2.save #Working as I expected ... record Inserted
# Case 3
p3 = Post.new({category_id: 30}) # A category with id 30 does not exists.
p3.save # Not working as I expected
在案例 3 中,我期待 Active Record 验证错误,例如 This Category does not exist 但我得到 一条 SQL 消息:
INSERT INTO "posts" ("category_id", "created_at", "updated_at") VALUES (?, ?, ?) [["category_id", 10], ["created_at", "2017-09-26 00:59:47.645185"], ["updated_at", "2017-09-26 00:59:47.645185"]]
ActiveRecord::InvalidForeignKey: SQLite3::ConstraintException: FOREIGN KEY constraint failed: INSERT INTO "posts" ("category_id", "created_at", "updated_at") VALUES (?, ?, ?)
【问题讨论】: