Pregunta

irb(main):044:0> i1.created_at
=> Thu, 24 Apr 2014 02:41:15 UTC +00:00
irb(main):045:0> i2.created_at
=> Thu, 24 Apr 2014 02:41:15 UTC +00:00
irb(main):046:0> i1.created_at == i2.created_at
=> false
irb(main):047:0> i1.created_at.to_time.to_i == i2.created_at.to_time.to_i
=> true

Seems not to work validates_uniqueness_of :created_at
because

irb(main):046:0> i1.created_at == i2.created_at
=> false

How to validate created_at? Don't want to save with the same date.

+++ UPDATE +++

irb(main):048:0> i1.created_at.class
=> ActiveSupport::TimeWithZone
irb(main):049:0> i2.created_at.class
=> ActiveSupport::TimeWithZone
¿Fue útil?

Solución

Since they might have different precision milliseconds.

Refer to the post: Testing ActiveSupport::TimeWithZone objects for equality

Chances are the millisecond values would be unequal.

puts i1.created_at.usec
puts i2.created_at.usec

Otros consejos

I think, if you are getting concurrent requests, there are chances that you may have multiple entries in the table which are created at same time and will have same time stamps.

As you said, if you don't want to save with the same date, you can put a lock while saving the entries, removing the possibility of creating two entries at same time. In that case validates_uniqueness_of :created_at should also work.

Just in case

class Item < ActiveRecord::Base
  attr_accessible :asin, :domain, :formatted_price, :user_id, :created_at

  validate :double_dates

  private

  def double_dates
    if Item.where(:user_id => self.user_id, :asin => self.asin, :domain => self.domain).where("DATE(created_at) = ?", Date.today).length >= 1
      errors.add(:created_at, "no double dates")
    end
  end
end
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top