我知道Rails以UTC存儲時間。ActiveRecord日期時間比較
我有日期時間
的out_date和in_date情況下,我有這個疑問:
reservations = Reservation.where("bookable_id = :bookable_id AND bookable_type = :bookable_type AND status <> :status AND ((:out_date >= check_out_date AND :out_date <= check_in_date) OR (:in_date <= check_in_date AND :in_date >= check_out_date) OR (:out_date <= check_in_date AND :in_date >= check_in_date))", :bookable_id => params[:bookable_id], :bookable_type => params[:bookable_type], :status => Reservation::STATUS_CHECKED_IN, :out_date => out_date, :in_date => in_date)
我總是空集,即使我應該得到回報的元組。
我嘗試了這些一些變體:
out_date.utc
out_date.utc.to_s(:db)
一切似乎是工作。如何構建這個查詢?
控制器代碼:
in_date = DateTime.strptime params[:checkin], "%Y-%m-%d %H:%M"
out_date = DateTime.strptime params[:checkout], "%Y-%m-%d %H:%M"
#check collision with non-recurring reservations
reservations = Reservation.where("bookable_id = :bookable_id AND bookable_type = :bookable_type AND status <> :status AND ((:out_date >= check_out_date AND :out_date <= check_in_date) OR (:in_date <= check_in_date AND :in_date >= check_out_date) OR (:out_date <= check_in_date AND :in_date >= check_in_date))", :bookable_id => params[:bookable_id], :bookable_type => params[:bookable_type], :status => Reservation::STATUS_CHECKED_IN, :out_date => out_date, :in_date => in_date)
logger.info(reservations)
if !reservations.empty?
@error_message = "This Asset has already been reserved for those dates"
return
end
同樣在導軌控制檯,簡單的查詢失敗:
1.9.3p0 :007 > Reservation.find_by_id 31
Reservation Load (0.7ms) SELECT `reservations`.* FROM `reservations` WHERE `reservations`.`id` = 31 LIMIT 1
=> #<Reservation id: 31, bookable_id: 11, bookable_type: "Asset", user_id: 1, check_out_date: "2012-07-07 08:00:00", check_in_date: "2012-07-07 10:00:00", notes: "rec", status: "Ready", is_recurring: true, repeat_count: 5>
1.9.3p0 :009 > Reservation.where " ? >= check_out_date AND ? <= check_in_date",DateTime.new(2012,7,7,9),DateTime.new(2012,7,7,9)
Reservation Load (0.5ms) SELECT `reservations`.* FROM `reservations` WHERE ('2012-07-07 09:00:00' >= check_out_date AND '2012-07-07 09:00:00' <= check_in_date)
=> []
「out_date」變量分配在哪裏? –
另外,你應該使用[命名範圍](http://ar.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html)。 –
@SimoneCarletti在同一個控制器中。 –