We have a simple item and order model.
orders(url)
items(title, orders_count)
Where “url” can be any URL from the web for e.g. http://amzn.to/aCKiXO. What we would like to do is that if the user enters “/items/7” for the “url” then have it behave like a foreign key. So something like:
class Order < ActiveRecord::Base
belongs_to :item, :foreign_key => :url, :regex => /items/n,
:counter_cache => true
end
class Item < ActiveRecord::Base
has_many :orders, :foreign_key => :url, :regex => /items/n,
:dependent => :destroy
end
Is this possible? We’re on Rails 2.3.8, Ruby 1.9.3 and on Postgresql 9.1
No, it isn’t possible to add a foreign key constraint that does a regular expression match – or anything except simple equality. See the PostgreSQL documentation on constraints.
What you can do is any of:
Write a constraint trigger in PL/PgSQL to enforce the constraint you want;
Split out the part you want to add a constraint on using a regexp in the application, and define a foreign key constraint on a column containing only that part; or
Use a
BEFORE INSERT OR UPDATE ... FOR EACH ROWtrigger to split the part of interest out in PL/PgSQL when the row is inserted and add the part of interest to a foreign key column that contains only that part. The app doesn’t need to know about the duplication since the DB is taking care of it behind the scenes.