Reputation: 6102
For example, I have two models:
class CheckInDetail < ApplicationRecord
belongs_to :product
end
class Product < ApplicationRecord
end
For example, when I insert CheckInDetail
, I add foreign key product_id
to hash params. I tried use some non-exist product id and column product_id
will be null. I want to throw exception when inserting like this.
There is a way that use validate
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).
Upvotes: 1
Views: 149
Reputation: 5633
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.
Upvotes: 1