Ruby-on-rails 在 Model 中访问 Devise 的 current_user

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5545116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:51:37  来源:igfitidea点击:

Access Devise's current_user in Model

ruby-on-railsruby-on-rails-3devise

提问by Kyle Decot

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.

如何访问模型内​​的 Devises 'current_user' 对象?我想在创建某些内容时自动将当前用户 ID 附加到记录中。我知道我可以在控制器内部手动设置 user_id 但我觉得如果它由模型处理会更容易/更干净。

回答by Kelly

Essentially, this kind of logic doesn't belong in a Model, so you're best to pass current_userin through a function in the model or on creation. This answersums it up.

本质上,这种逻辑不属于模型,因此您最好current_user通过模型中的函数或在创建时传入。这个答案总结了它。

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.

我知道,我知道,这不是你想要的答案。不幸的是,它可能看起来更干净,但它会增加您真正不想要的模型的开销。