2009-09-03 61 views
3

MySQL允許的0000-00-00date領域,但是ActiveRecord治療的分配給一個Date值與字符串爲nil值。插入一個無效的ActiveRecord的日期到MySQL數據庫

我有一個遺留應用程序依賴於確切的字段內容爲「從不」,所以如果客戶的最後付款日期是0000-00-00它承認爲「從不」支付。

有沒有一種方法可以覆蓋ActiveRecord(正確)此date字段的驗證並將此值寫入數據庫而不會弄髒我的手(太)?

感謝您的任何見解。

回答

2

你會發現這個稍微容易一些,它應該得到同樣的結果,而不執行方法,每個屬性模型

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 
+0

這似乎是古代的Rails,Rails 2也許? – Smar 2016-04-05 11:29:26

1

我討厭回答我的問題,而是關於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 

我將離開這個問題的情況下,打開有人有更好的方法或想評論可能的缺陷。

0

您可以在數據庫上使用適當的SQL改變表改變列更改默認值是「0000-00-00」 ......;聲明。

4

我在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