In the Rails 3 model, DateTime attributes are falsely dirty.

In my Rails 3 application, I want to write an entry only in a specific log, if the changes are really made in the model. Therefore, if the user does not change any of the fields and clicks Submit, then there should be no journal 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 both of them return true, which I think will be a contradiction.

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

I am wondering if this is due to a change in the default date format in the initializer (to "% m /% d /% Y") or, possibly, time zones.

I'm at a dead end, so any help would be greatly appreciated.

+6
source share
3 answers

You can change the default date and time format in the local en.yml file as follows: (this is an example for the 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 just 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 this helps you.

+2
source

I understand when you asked, you probably used a different version of Rails, but I just stumbled upon it myself with Rails 3.2.5. Apparently his regression in 3.2.5 too: https://github.com/rails/rails/issues/6591

+1
source

I came here from a Google search engine for a similar problem. It was not related to the Rails version, but after some debugging, I found out that I assigned a Time object with milliseconds. When calling changed I got back and an array of seemingly identical objects, since it was converted to DateTime . Not sure if this can be considered an error in Rails or not, but in case you end up with the same problem, make sure you don't assign a datetime with milliseconds to them.

+1
source

Source: https://habr.com/ru/post/887037/


All Articles