0

I have a table to enter Vehicle Names, model name is Vehicle I dont want name to repeat..so i have

validates_uniqueness_of :make, :case_sensitive => false

in my model. Thing is I have used soft delete to delete a record by setting is_deleted flag field to true. This is_deleted column is also present in Vehicle model.

So the problem is if I delete 1 table it just soft-deletes it and when I try to create one vehicle with same name which was soft-deleted then error occures because of validation as the field is not originaly deleted from DB.

Is there a simple way to solve this issue.

Nidhin S G
  • 1,685
  • 2
  • 15
  • 45
  • possible duplicate of [Rails validate uniqueness only if conditional](http://stackoverflow.com/questions/20914899/rails-validate-uniqueness-only-if-conditional) – Brad Werth Aug 06 '14 at 05:50

2 Answers2

0

I believe this should do the trick:

validates_uniqueness_of :make, :case_sensitive => false, unless: :is_deleted
Nobita
  • 23,519
  • 11
  • 58
  • 87
  • 1
    Don't think that will work - the validation will only be applied to non deleted rows, but the search will still find deleted rows – Frederick Cheung Aug 06 '14 at 07:03
  • It won't work, but you can add is_deleted to the validation scope and combined with this unless condition it should work. – Qwertie Sep 01 '22 at 03:25
-1

Conditions

From the sounds of it, you'll want to use a conditional validation, which will look up the name with the constraints of it not having is_deleted? attribute set to true:

#app/models/your_model.rb
Class YourModel < ActiveRecord::Base
    validates :make, uniqueness: { scope: :name, message: "Only One Name Allowed Sorry!" }, if: :is_unique?

    def is_unique?
       return Model.find_by({name: name, is_deleted: false}) #-> will look up any data records which have is_deleted as false & same name
    end
end
Richard Peck
  • 76,116
  • 9
  • 93
  • 147