Seems like a pretty straightforward question, but I can't seem to locate the specific answer anywhere online.
I have a price
model that references both quote and a line item, thus it has quote_id
and line_item_id
columns. I am using a multicolumn index with unique: true
to prevent multiple prices for the same line_item from being attached to a quote. quote_id
is the first column in the index.
However, I want to allow users to add prices to line_items
that haven't been quoted. It works fine for one price, quote_id
is null and line_item_id
is present. However, the unique index is preventing me from attaching a second price to the same line_item
. The null value in quote_id
is being treated as unique.
Is there any way to make the unique constraint only apply when the quote is not null?
I know that allow_nil
can be used in model validation, but can it be used in the index?
I am thinking something like:
add_index :prices, [:quote_id, :line_item_id], :unique => true, :allow_nil => true
PostgreSQL and Rails 4.