我有一个应用程序,当前有两种类型的用户,管理员和供应商,我想记录他们的活动,如
"TestAdmin" viewed transaction
"TestAdmin" added a new vendor
"TestAdmin" edited a Transaction
"TestVendor" added a new Transaction
"TestAdmin" approved Transaction
"TestAdmin" rejected Transaction
etc...
其中“TestAdmin”是管理员,“TestVendor”是供应商</ p>
但我不确定我应该遵循什么方法
我想到了这个
在DB中添加具有以下字段的活动表
user_id
browser
session_id
ip_address
action
params
并致电
before_filter :record_activity
记录所有活动
但不确定如何创建上述消息
此外,我想弄清楚是否有任何错误发生以及何时以及为什么,所以对于这个我需要浏览器字段来确定代码是否在IE等中不起作用但这只是一个错误跟踪字段。
请帮助并指导一些很好的方法来实现这一目标。
由于
答案 0 :(得分:23)
好的,这就是我做的......
首先创建表
create_table "activity_logs", :force => true do |t|
t.string "user_id"
t.string "browser"
t.string "ip_address"
t.string "controller"
t.string "action"
t.string "params"
t.string "note"
t.datetime "created_at"
t.datetime "updated_at"
end
在应用程序控制器中创建了函数
def record_activity(note)
@activity = Activity_Log.new
@activity.user = current_user
@activity.note = note
@activity.browser = request.env['HTTP_USER_AGENT']
@activity.ip_address = request.env['REMOTE_ADDR']
@activity.controller = controller_name
@activity.action = action_name
@activity.params = params.inspect
@activity.save
end
然后从任何需要的控制器调用上面的函数 像这样....
class AccountsController < ApplicationController
load_and_authorize_resource
# POST /accounts
# POST /accounts.json
def create
@account = Account.new(params[:account])
respond_to do |format|
if @account.save
record_activity("Created new account") #This will call application controller record_activity
format.js { head :ok }
else
format.js { render json: @account.errors, :error => true, :success => false }
end
end
end
因此问题解决了......
感谢所有人的帮助......
答案 1 :(得分:8)
在rails中有几个插件可以在模型上实现这种功能。我用acts_as_audited来满足我的要求。
我开始了解另外一个record_activities,但对此却知之甚少。希望它对你有帮助!
答案 2 :(得分:3)
这是“活动”记录的绝佳宝石...... https://github.com/pokonski/public_activity
答案 3 :(得分:1)
我认为你应该设置模型函数来捕获像after_save
,after update
这样的动作,如果你的模型是日志表的字段,那么事件可以是
user_id,
model_name,
action,
ip_address,
session_id,
params
答案 4 :(得分:1)
我建议你在“活动”数据库中使用这些字段:
model = name of the model ex. "Vendor", "Transaction"
user_id = id of user
belongsTo = id of user that own the action/created the action etc..
action = name of the action
并在“活动模型”上添加一个功能
log_activity(model, user_id, belongsTo, action)
log = Activity.new
log.model = model
log.user_id = user_id
log.belongsTo = belongsTo
log.action = action
log.save
end
then in you other models that you want to log add callbacks like:
before_create :log
before_update :log
before_destroy :log
def log
Activity.log_activity(self.class, self.user_id, self.belongsTo, self.action)
# assuming you have this fields on you forms
end
答案 5 :(得分:1)
我不得不说@Anil D的答案显然是耦合的。对于小型项目来说这是可以的,但随着项目越来越大,它将导致严重的问题(开发,调试,维护问题)。
我更喜欢审核:(https://github.com/collectiveidea/audited),这是一个简单的&amp;仅针对用户活动的清洁解决方案。它支持Rails3和关联。