class TripdateValidator < ActiveModel::EachValidator def validate_each(object,attribute,value) # Check value exists as end_date is optional if value != nil parsed_date = Date.parse(value) # is the start date within the range of anything in the db trips = Trip.where(['start_date >= ? AND end_date <= ? AND user_id = ?',parsed_date,object.user_id]) # overlapping other trips,aghhh object.errors[attribute] << 'oh crap' if trips end end end
日期来自一个type =“date”字段,由jQuery UI Datepicker驱动,并包含格式2011-01-01.这可能是2011-01-30 00:00:00 UTC,我不完全明白.
如果我尝试对此值使用Date.parse(),它会给出错误:
TypeError in TripsController#create
$_ value need to be String (nil given)
Rails.root:
/Users/phil/Sites/travlrapp.com
Application Trace | Framework Trace |
Full Traceapp/models/trip.rb:29:in
validate_each'
create’
app/controllers/trips_controller.rb:75:in
app/controllers/trips_controller.rb:74:in
`create’
无论何时运行查询,都不返回任何内容.这可能是一个日期格式的问题,我的逻辑是坏的还是我做的事情真的很愚蠢?被困在这一段时间,谷歌没有帮助.
编辑人们正在关注Date.parse错误,但这不是主要的问题.当我遇到困难时,我不明白当一切都是完全不同的格式时,如何做日期比较.
我已经为Chronic.parse()交换了Date.parse(),现在我收到以下生成的SQL查询:
SELECT "trips".* FROM "trips" WHERE (start_date >= '2011-01-26 00:00:00.000000' AND end_date <= '2011-01-26 00:00:00.000000' AND user_id = 19)
这没有回报.我正在测试的日期是:
开始:2011-02-17 00:00:00.000000
结束:2011-02-21 00:00:00.000000
看到我认为日期正在格式正确现在它似乎更像一个逻辑问题.如何验证重叠日期> ;.
解决方法
$gem安装squeel
model.rb
Model.where{date_colum > 10.years.ago & date_column < DateTime.now}