0

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?

worrawut
  • 958
  • 10
  • 17
  • you can create a hook method and use `before: hook_method_name` to handle this too.. – Arup Rakshit May 02 '14 at 08:32
  • You are validating that the `submit_date` is unique based on `name` since `nil` is unique in comparison to `2014-05-02` this will pass. What do you want to happen if the initial record has a `nil` `submit_date`? Do you want to update it ? – engineersmnky May 02 '14 at 14:58
  • @engineersmnky Yes, I expect to have a nil on submit_date for any new record added. When the name, let's say LotB, is actually submitted then I would like to have the record of LotB in this table update value of submit_date. But I would like to prevent (do not want) the duplicated LotB to be added into the table. – worrawut May 03 '14 at 15:44

1 Answers1

0

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 
engineersmnky
  • 25,495
  • 2
  • 36
  • 52