Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Rails 3 model, DateTime attributes are falsly "dirty"

In my Rails 3 application, I only want to write an entry in a certain log if changes are actually made to a model. So if a user doesn't change any of the fields and clicks 'Submit', then there should not be a log entry.

But it seems that no matter what, Rails always seems to think that the DateTime attributes of the model have been changed.

When I debug, I run the following lines during my update and they both return true, which I would think would be a contradiction.

@request.begin_date == @request.begin_date_was  # Returns true
@request.begin_date_changed?  # Returns true

I'm wondering if it has something to do with changing the default date format in an initializer (to '%m/%d/%Y') or possibly something with time zones.

I'm stumped, so any help would be greatly appreciated.

like image 636
Adam Albrecht Avatar asked May 01 '11 01:05

Adam Albrecht


1 Answers

You can change default date and time format in your en.yml locale file like this: (this is example for french format in one of my projects)

date:
 formats:
  default: "%d/%m/%Y"
  short: "%e %b"
  long: "%e %B %Y"
  long_ordinal: "%e %B %Y"
  only_day: "%e"
time:
 formats:
  default: "%d %B %Y %H:%M"
  time: "%H:%M"
  short: "%d %b %H:%M"
  long: "%A %d %B %Y %H:%M:%S %Z"
  long_ordinal: "%A %d %B %Y %H:%M:%S %Z"
  only_second: "%S"
 am: 'am'
 pm: 'pm'

Or you can simply convert your datetime instances to:
@request.begin_date.strftime("%m/%d/%Y") == @request.begin_date_was.strftime("%m/%d/%Y") or even:
l(@request.begin_date, :format => your_format_in_locale_file) == l(@request.begin_date_was, :format => your_format_in_locale_file)

Hope it will help you

like image 172
bor1s Avatar answered Oct 24 '22 07:10

bor1s