【问题标题】:Recommended practice for passing current user to model将当前用户传递给模型的推荐做法
【发布时间】:2015-02-24 13:30:05
【问题描述】:

给定一个模型Orderstatus 和属性private_status:stringprivate_status_history:json(我使用的是Postgresql 的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.或者,有什么重构应用程序结构的建议?

【问题讨论】:

  • 在不相关的说明中,您是否有理由手动执行此操作而不是使用 paper trail 之类的东西?
  • 感谢您的来信。老实说,paper-trail 肯定适合,但因为现在这是我需要跟踪的唯一属性;我宁愿手动操作以避免向堆栈添加新的 gem。另外,我正在讨论实现这一目标的有趣方法:)

标签: ruby-on-rails ruby json postgresql


【解决方案1】:

所以,我最终选择了这个选项(我希望它不会让任何人感到震惊: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

注意事项: - 我通过类Orderstatus 的实例属性modifying_user 将控制器传递给模型。该属性未保存到数据库中。 - 更改将新更改附加到历史字段的方法。 IE。 attr_will_change! + saveupdate_column + append

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 2013-01-17
    • 2022-10-23
    相关资源
    最近更新 更多