访问模型中设备的 current_user
如何访问模型内部的 Devises 'current_user' 对象?我想在创建某些内容时自动将当前用户 ID 附加到记录中。我知道我可以在控制器内部手动设置 user_id,但我觉得如果由模型处理它会更容易/更干净。
How do I go about accessing Devises 'current_user' object inside of a model? I want to automatically append the current users id to a record when they create something. I know that I can manually set the user_id inside of the controller but I feel it would be easier/cleaner if it was handled by the model.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
本质上,这种逻辑不属于模型,因此您最好通过模型中的函数或在创建时传递
current_user
。 这个答案总结了这一点向上。我知道,我知道,这不是你想要的答案。不幸的是,它对您来说可能看起来更干净,但它增加了您真正不想要的模型的开销。
Essentially, this kind of logic doesn't belong in a Model, so you're best to pass
current_user
in through a function in the model or on creation. This answer sums it up.I know, I know, that's not the answer you wanted. Unfortunately, it may be cleaner looking to you, but it adds overhead to your model that you really don't want.
许多流行的gem需要访问模型中的
current_user
,例如paper_trail< /a>.他们的方法从捕获
current_user
的控制器开始。哪个触发器:
以及
从控制器保存
current_user.id
后,触发审核操作(例如创建)。最终触发以下事件。
总之,一种方法如下。
before_action
保存current_user
将current_user
存储在模型中的paper_trail
中稍后可以访问的位置code> 的情况是PaperTrail.request.whudunnit
Many popular gems need to access the
current_user
in the model such as paper_trail.Their approach starts in the controller which captures the
current_user
.Which triggers:
and
After the
current_user.id
is saved from the controller, and an auditing action is triggered such as create.Which eventually triggers the following event.
In summary, an approach would be the following.
current_user
using abefore_action
in a controllercurrent_user
somewhere that can be accessed later in the model, inpaper_trail
's case that isPaperTrail.request.whudunnit