Trần Kim Dự Trần Kim Dự - 2 months ago 6
Ruby Question

ActiveRecord: how to throw exception when reference key not exist

For example, I have two models:

class CheckInDetail < ApplicationRecord
belongs_to :product

class Product < ApplicationRecord

For example, when I insert
, I add foreign key
to hash params. I tried use some non-exist product id and column
will be null. I want to throw exception when inserting like this.

There is a way that use
on model for checking that field before inserting. But I think this will cost time (because I insert bunch of items) and not really necessary because client doesn't do that. (just in case something really went wrong).


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

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.