before_save回调应根据以下代码将过期字段值更新为true
或false
:
class Package < ActiveRecord::Base
before_save :update_availabiltiy
def update_availabiltiy
self.expired = date_end.to_date < Date.today
end
end
但除非此字段的值与存储的值相同,否则它将无法工作:例如:如果此字段在DB中为真且回调中的条件将评估为true,则将保存记录,否则控制器将返回400
Started PUT "/api/venues/bogan-and-sons/packages/delicious-package" for ::1 at 2016-09-20 15:20:03 +0300
Processing by Api::PackagesController#update as JSON
Parameters: {"package"=>
{"date_start"=>"2016-08-27T00:00:00.000-04:00", "date_end"=>"2016-12-30, ...}
}
(0.2ms) BEGIN
(0.1ms) ROLLBACK
Completed 400 Bad Request in 81ms (Views: 0.6ms | ActiveRecord: 17.8ms)
object.errors返回空数组,因此不存在对象的实际错误。
更新安德烈:
[31, 40] in /Users/srosca/projects/venuezz/app/models/package.rb
31: !expired || (Date.today <= self.date_end.to_date)
32: end
33:
34: def update_availabiltiy
35: byebug
=> 36: self.expired = date_end.to_date < Date.today
37: end
38:
39: def calculate_discount
40: if discount_price
(byebug) expired
true
(byebug) date_end.to_date < Date.today
false
(byebug) self.expired = date_end.to_date < Date.today
false
(byebug) expired
false
答案 0 :(得分:1)
错误的原因是before_save
挂钩能够通过返回false
取消保存操作(这是当您的记录未过期时会发生的情况。
返回其他内容,而不是作业结果。例如:
def update_availabiltiy
self.expired = date_end.to_date < Date.today
true # no canceling
end