For example, I have two models:
class CheckInDetail < ApplicationRecord
class Product < ApplicationRecord
This is one of the benefits of relational databases, as you could add a foreign_key reference to your migration and everything should work perfectly.
You could run a migration with
rails g migration add_foreign_key_to_check_in_details
in the migration, you should add something like:
class AddForeignKeyToCheckInDetails < AR::Migration def change remove_foreign_key :check_in_details, :products add_foreign_key :check_in_details, :products, dependent: :delete end end
With this in place all attempts to save a non existent product will fail. Also ensure to add a NOT NULL constraint to your
product_id column, as attemts to save a check_in_detail with a null product_id will succeed. The update to the migration would look like:
change_column :check_in_details, :product_id, :integer, null: false
Let me know if that answers your question.