MySQL允许将0000-00-00作为date字段的值,但是ActiveRecord会将对包含该字符串的Date值的赋值视为nil。
我有一个遗留应用程序,它依赖于“从不”概念的确切字段内容,所以如果客户最后一次付款日期是0000-00-00,它就会确认为“从未”付款。
有没有一种方法可以覆盖此date字段的ActiveRecord (正确)验证,并将此值写入数据库,而不会弄脏我的手?
谢谢你的见解。
发布于 2009-09-04 04:49:05
您可能会发现这稍微容易一些,而且无需对模型中的每个属性执行方法,就可以达到相同的结果
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发布于 2012-10-08 11:48:18
我在一个Rails 3.0.3项目中遇到了这个问题,monkey修补了以下内容,允许您将'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发布于 2009-09-03 15:52:04
我讨厌回答自己的问题,但在对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我会留下这个问题,以防有人有更好的方法或想要评论可能的缺陷。
https://stackoverflow.com/questions/1374096
复制相似问题