使用after_save回调将updated_by列设置为当前用户。

6

我想使用after_save回调将updated_by列设置为current_user。但是模型中无法使用current_user。我该如何做到这一点?

2个回答

8
你需要在控制器中处理它。首先在模型上执行保存操作,如果成功则更新记录字段。
示例
class MyController < ActionController::Base
  def index
    if record.save
      record.update_attribute :updated_by, current_user.id
    end
  end
end

另一种选择(我更喜欢这种方法)是在您的模型中创建一个自定义方法来包装逻辑。例如:

class Record < ActiveRecord::Base
  def save_by(user)
    self.updated_by = user.id
    self.save
  end
end

class MyController < ActionController::Base
  def index
    ...
    record.save_by(current_user)
  end
end

将其放入模型中的原因是DRY,因为save()可以从应用程序中的许多位置调用,而不仅仅是一个控制器。我宁愿只做一次,而不必重复自己,并担心始终记得设置这个。 - pixelearth
然后创建一个新的方法,例如Model.save_from_user(user),并在其中放置保存记录和执行touch的逻辑。然后,在您的控制器中,只需调用该方法并传递“current_user”作为参数即可。 - Simone Carletti
嗨Simone,根据您的建议,我已经实现了monkeypatch(如下所示),据我所知,touch只会更改时间戳,而不是用户ID。您是否发现任何问题?这是为了与设备当前用户一起使用。非常感谢您的任何意见! - Matt

1

我按照Simone Carletti的建议实现了这个monkeypatch,据我所知touch只会更改时间戳而不会更改用户ID。这样做有什么问题吗?这是为了与devise的current_user一起使用。

class ActiveRecord::Base
  def save_with_user(user)
    self.updated_by_user = user unless user.blank?
    save
  end 

  def update_attributes_with_user(attributes, user)
    self.updated_by_user = user unless user.blank?
    update_attributes(attributes)
  end  
end

然后createupdate方法会这样调用它们:

@foo.save_with_user(current_user)
@foo.update_attributes_with_user(params[:foo], current_user)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接