Skip to content
Advertisement

Ruby Foreign Key Constraints in Database vs Model

I have the following models in a Rails app. This setup has worked fine since normally when I would like to add a new VendorPromo to a vendor, there’s a dropdown in the view of available Promos to choose from. Now, I’m enabling the creation of new VendorPromos via an API. However, this current set up will allow the creation of a VendorPromo with any promo_id, even if it doesn’t exist in Promo. I’ve seen the belongs_to :promo, foreign_key: :promo, and I know you can add a foreign key constraint via the DB as well. What I’d like to know is the difference between these two approaches and if one is better?

Edit: I recognize that application constraints are different than DB constraints, but when I apply the constraint in the app, i.e. the belongs_to :promo, foreign_key: :promo it doesn’t actually seem to enforce the constraint at all. Specifically, I can create a new VendorPromo with a promo_id of, say, 13, even though Promo only has IDs between 1 and 8.

class Vendor
  has_many :vendor_promos
end

class VendorPromo
  belongs_to :vendor
  belongs_to :promo
end

class Promo
end

Advertisement

Answer

Juan Carlos’s answer was part of the way there. It’s true that the foreign_key attribute in belongs_to does not enforce any database or application level foreign key. What I was looking for was the belongs_to :promo, optional: false flag does in fact enforces an application level foreign key. That flag, in addition to a DB level foreign key constraint resolved my issue.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement