[英]Passing a variable in an after_update action
I have an UserProfile
model:我有一个UserProfile
model:
class UserProfile < ApplicationRecord
after_update :check_changes
def check_changes
AuditRecord.create(account_id: self.id, fields: self.saved_changes , account_type: 'UserProfile', admin_id: 3) if self.saved_changes?
end
id ID | user_id用户身份 | name名称 | last_name姓 |
---|---|---|---|
1 1个 | 1 1个 | john约翰 | doe母鹿 |
2 2个 | 2 2个 | foo富 | bar酒吧 |
and AuditRecord
model:和审计记录AuditRecord
:
id ID | account_type帐户类型 | account_id帐户ID | field场地 | admin_id admin_id |
---|---|---|---|---|
1 1个 | UserProfile用户资料 | 1 1个 | {} {} | 3 3个 |
2 2个 | UserProfile用户资料 | 2 2个 | {} {} | 3 3个 |
This AuditRecord
saves all of the updates of the profiles, but could be updated by different admins.此AuditRecord
保存配置文件的所有更新,但可以由不同的管理员更新。
How can I send to check_changes
function the admin_id?如何将 admin_id 发送到check_changes
function? Because right now always is going to be 3.因为现在总是 3。
Admin
, which is related to AuditRecord
in some way.如果我理解正确,您只想将 admin_id 传递给 AuditRecord,这意味着您需要另一个 model Admin
,它在某种程度上与AuditRecord
相关。Admin
model, set up the appropriate active record association and references.首先生成Admin
model,设置适当的活动记录关联和引用。 Rails docs for this Rails 文档为此admin.auditrecords
depending upon how you set up the associations.您现在应该能够访问关联,根据您设置关联的方式,使用类似admin.auditrecords
的内容。after_update
is called automatically. after_update
被自动调用。 You can't pass some variables there dynamically你不能在那里动态传递一些变量
But you can evenly distribute tasks between admins但是您可以在管理员之间平均分配任务
class AuditRecord < ApplicationRecord
class << self
def most_free_admin_id
select(:admin_id).
group(:admin_id).
order('COUNT (admin_id)').
first.
admin_id
end
end
end
AuditRecord.most_free_admin_id
will generate SQL like this AuditRecord.most_free_admin_id
会像这样生成 SQL
SELECT admin_id
FROM audit_records
GROUP BY admin_id
ORDER BY COUNT (admin_id)
LIMIT 1;
It will return id of the admin who has the least audit records它将返回拥有最少审计记录的管理员的 ID
Also it's better to create such records not after update, but after commit when record is 100% saved in DB.此外,最好不要在更新之后创建此类记录,而是在记录 100% 保存在数据库中时提交之后创建。 For this purpose after_update_commit
is better为此, after_update_commit
更好
Also in Ruby we use self.
同样在 Ruby 中我们使用self.
only in situations where it is impossible without it只有在没有它就不可能的情况下
Finally you can apply it in the model最后可以在model申请
class UserProfile < ApplicationRecord
after_update_commit :check_changes
private
def check_changes
AuditRecord.create(
account_id: id,
fields: saved_changes,
account_type: 'UserProfile',
admin_id: AuditRecord.most_free_admin_id
)
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.