Search code examples
rubyvalidates-uniqueness-of

how to use validates_uniqueness_of with condition


I'm using datamapper with ruby. I would like to validate my new data set before insert it into the table. My validation criteria are..

1) to insert only if the field 'name' is not exist.

2) Not insert if the record with the same 'name' has already have 'submit_date' (not null).

I looks on dm-validations and I think validates_uniqueness_of should help. I try following code

validates_uniqueness_of :submit_date, :scope => :name

but the result is not as I expect. the same 'name ' still added into the table while its existing 'name' already has 'submit_date' value.

id|name|submit_date|
1 |LotA|Null
2 |LotB|2014-05-02
3 |LotB|Null <--- This record should not be added because LotB is existing and already submit
4 |LotC|Null

Any advise, pls?


Solution

  • If your intention is to validate uniqueness of name first then you could do this

    validates :name, presence: true, uniqueness:{case_sensitive:false}
    validate :exists_with_submit_date
    
    def exists_with_submit_date
        existing_record = self.find_by_name(name) 
        if existing_record && existing_record.submit_date
          errors.add(:name, "all ready exists with submit_date #{existing_record.submit_date}")
        end
    end