pix*_*rth 6 ruby ruby-on-rails ruby-on-rails-3
我想使用after_save回调将updated_by列设置为current_user.但是current_user在模型中不可用.我该怎么做?
您需要在控制器中处理它.首先在模型上执行保存,然后如果成功更新记录字段.
例
class MyController < ActionController::Base
def index
if record.save
record.update_attribute :updated_by, current_user.id
end
end
end
Run Code Online (Sandbox Code Playgroud)
另一种选择(我更喜欢这个)是在模型中创建一个包装逻辑的自定义方法.例如
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2070 次 |
| 最近记录: |