给定具有属性Orderstatus
和private_status:string
的模型private_status_history:json
(我使用Postgresql' s json )。我想记录每个状态转换,以及进行更改的用户。
理想情况下会是这样的:
class Orderstatus < ActiveRecord::Base
after_save :track_changes
def track_changes
changes = self.changes
if self.private_status_changed?
self.private_status_history_will_change!
self.private_status_history.append({
type: changes[:private_status],
user: current_user.id
})
end
end
end
class OrderstatusController <ApplicationController
def update
if @status.update_attributes(white_params)
# Good response
else
# Bad response
end
end
end
#Desired behaviour (process not run with console)
status = Orderstatus.new(private_status:'one')
status.private_status #=> 'one'
status.private_status_history #=> []
status.update_attributes({:private_status=>'two'}) #=>true
status.private_status #=> 'two'
status.private_status_history #=> [{type:['one','two'],user:32]
实现这一目标的推荐做法是什么?除了通常使用Thread之外。或者,是否有任何重构应用程序结构的建议?
答案 0 :(得分:0)
所以,我最终选择了这个选项(我希望这对任何人来说都不会令人担忧:S)
class Orderstatus < ActiveRecord::Base
after_save :track_changes
attr_accessor :modifying_user
def track_changes
changes = self.changes
if self.private_status_changed?
newchange = {type:changes[:private_status],user: modifying_user.id}
self.update_column(:private_status_history,
self.private_status_history.append(newchange))
end
end
end
class OrderstatusController <ApplicationController
def update
@status.modifying_user = current_user # <---- HERE!
if @status.update_attributes(white_params)
# Good response
else
# Bad response
end
end
end
注意:
- 我通过类modifying_user
的实例属性Orderstatus
将Controller从Controller传递给Model。该属性未保存到数据库中。
- 更改方法以将新更改附加到历史记录字段。即attr_will_change! + save
至update_column + append