0

My model validation isn't working as expected although the DB validation works fine.

I need to have a unique constraint on the combination of 3 attributes together. The validation should be that if :tag_owner_area is present, there should be no other rows in the table that have the same tag_owner_area, fieldable_type and fieldable_id.

Field.rb model has the following validation:

validates :tag_owner_area, :allow_blank => true, uniqueness: {scope: [:fieldable_type, :fieldable_id]}

Which I thought was validating for the same conditions as the PostgreSQL validation:

create_table :fields do |t|
  t.integer :tag_owner_area
  t.references :fieldable, polymorphic: true, index: true, :null => false
  t.references :user, foreign_key: true
  t.timestamps
end

# Here is the validation that works as intended
add_index :fields, [:tag_owner_area, :fieldable_type, :fieldable_id],unique: true, :name => 'field_unique_index' 

There must be a difference though since the DB validation is set off as expected but the model validation doesn't seem to be triggered.

P0lska
  • 461
  • 1
  • 6
  • 17

0 Answers0