I am using Rails version 5.1.3.

Does Rails have a way to validate if the foreign key value exists in an optional relationship?

I have the next model:

```ruby
class Post < ApplicationRecord

  belongs_to :category, optional: true
  validates :category, presence: true, allow_nil: true

end

```

This is the migration:

```ruby
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

```

These are the cases:

```ruby
# 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 

```

In the case 3 I was expecting an Active Record validation error something like This Category does not exists but instead of I get
 an SQL message: 

```ruby
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 (?, ?, ?)

```