Inserting an invalid ActiveRecord date in a MySQL database

MySQL allows a value 0000-00-00for fields date, but ActiveRecordconsiders assignment to a value datewith this string as nil.

I have an outdated application that relies on this exact content of the field for the concept of "Never", so if the client’s last payment date 0000-00-00, he acknowledges that he never paid.

Is it possible to override the ActiveRecord(correct) check for this field dateand write this value to the database without even polluting my hands?

Thank you for understanding.

+3
source share
4 answers

,

class CustomerInfo < BillingDatabase
  belongs_to :customer

  def lastpaid
    value = read_attribute(:lastpaid)
    value.blank? ? "0000-00-00" : value
  end
end

, , , read_attribute lastpaid . / .

def lastpaid
  read_attribute(:lastpaid).blank? "0000-00-00" : read_attribute(:lastpaid)
end
+2

Rails 3.0.3, , '0000-00-00' . mysql /.

  class ActiveRecord::ConnectionAdapters::Column
    def self.string_to_date_with_zero_support(string)
      return string if string == '0000-00-00'
      string_to_date_without_zero_support(string)
    end

    class << self
      alias_method_chain(:string_to_date, :zero_support)
    end
  end
+4

, AR- :

class CustomerInfo < BillingDatabase
  belongs_to :customer

  alias_method :old_read_attribute, :read_attribute

  def read_attribute(attr_name)
    if attr_name == "lastpaid" and old_read_attribute(attr_name).blank?
      "0000-00-00"
    else
      old_read_attribute(attr_name)
    end
  end
end

, - .

+1

You can change the default value in the database as "0000-00-00" using the corresponding alter sql column alter alter ...; statement.

0
source

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


All Articles