我的情况是"变化"我的对象有几个字段,其中field_was值为nil,但数据库中肯定有数据。
该模型看起来有点像这样(我已经删除了一些访问者):
class Attendance < ActiveRecord::Base
include Models::VersionLogger
belongs_to :target, polymorphic: true
state_machine :status, initial: :pending do
state :pending
state :confirmed
event :confirm do
transition pending: :confirmed
transition confirmed: :confirmed
end
event :pending do
transition any => :pending
end
after_transition :pending => :confirmed do |attendance|
# do something not relevant
end
end
after_update do
puts changes
do_something_that_uses_changes_or_was
end
after_initialize do
if new_record?
if DateTime.now.month === 12
self.period = DateTime.now.to_date..DateTime.now.end_of_year.next_year.to_date
else
self.period = DateTime.now.to_date..DateTime.now.end_of_year.to_date
end
end
end
end
这很好用。特别是,&#34;放置变化&#34;例如,如果我调用x.confirm,则在after_update中输出正确的数据。
调用它的控制器看起来有点如下:
class Thing::RoomMembershipsController < AuthenticatedUserController
expose(:room_membership, model: :attendance, ancestor: :attendances) do |object|
object.becomes Attendance
end
def update
room_membership.assign_attributes resource_params
room_membership.save
end
private
def resource_params
sti_class = :attendance if params.has_key? :attendance
sti_class = :room_membership if params.has_key? :room_membership
params.require(sti_class).
permit(:target_id, :target_type, :period, :type, :status, days: []).
merge(required_params)
end
def attendances
current_thing.attendance_details
end
def required_params
if request.xhr?
{type: 'RoomMembership', status_event: 'pending'}
else
{type: 'RoomMembership', status_event: 'confirm'}
end
end
end
&#34; resource_params&#34;正在返回{"target_id"=>"16", "target_type"=>"Room", "period"=>"2015/11/10 - 2016/12/31", "type"=>"RoomMembership", "days"=>["1", "2", "3", "4", ""], "status_event"=>"confirm"}
例如,作为PATCH的一个例子。
如果我发现()数据库中的出席并对其进行状态更改,则一切正常(例如x.find(nnn).confirm)。
但是当PATCH如上所述进入时,&#34;会发生变化&#34;在after_update中输出如下内容:
{"status"=>[nil, "confirmed"], "period"=>[nil, Tue, 10 Nov 2015..Sat, 31 Dec 2016], "days"=>[[1, 2, 3], [1, 2, 3, 4]], "updated_at"=>[Thu, 31 Mar 2016 00:19:16 AEDT +11:00, Thu, 31 Mar 2016 00:28:02 AEDT +11:00]}
那些罪恶杀了我。这意味着我无法判断这段时间是否真的发生了变化,这对我来说非常重要。而且它只是那两个领域。其他领域工作正常(例如天很好)。
但这是最奇怪的修复(在调试时意外发现)。如果我只是访问&#34;更改&#34;在after_initialize中,一切正常:
after_initialize do
if new_record?
if DateTime.now.month === 12
self.period = DateTime.now.to_date..DateTime.now.end_of_year.next_year.to_date
else
self.period = DateTime.now.to_date..DateTime.now.end_of_year.to_date
end
end
changes
end
那就是它!这解决了它。现在,更改在after_update中具有正确的status_was和period_was值。但为什么?我讨厌一个对我没有意义的解决方案,因为我无法解释它是如何工作的,这意味着我不知道什么时候它会停止工作。关于控制器如何实例化模型或assign_attributes如何工作,有什么奇怪的吗?