有哪些好的方法可以获取模型中的当前用户详细信息? [英] What are good ways to get current user detail in models?

查看:98
本文介绍了有哪些好的方法可以获取模型中的当前用户详细信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Rails应用程序中使用了devise gem进行身份验证.我想在after_create回调中获取有关当前用户的某些信息.这怎么可能?
我的模型代码是:

I used devise gem for authentication in my rails application. I want to get certain information about current user on after_create callback. How is it possible?
My model code is:

class Department
  field :name
  after_create :create_news
  private
  def create_news
    @user = current_user
  end
end

但是当我创建新部门时,出现以下错误.

But when I create new department I get following error.

undefined local variable or method `current_user' for #<Department:0x00000005b51648>

最好的方法是什么?

推荐答案

rails中的访问控制是在控制器级别而不是模型级别完成的.结果,Rails没有提供从内部模型代码访问当前用户,Cookie等的机制.您可以根据需要将参数通过方法传递到模型中.但是,这将忽略业内一些最佳程序员的设计决策,因此我认为这可能不是一个好选择.

Access control in rails is done at the controller level, not the model level. As a result, rails provides no mechanism for accessing the current user, cookies, etcetera, from inside model code. You can ferry the data into the model by parameters to methods, if you choose. However, that would be ignoring the design decisions of some of the best programmers in the industry, so I think it's probably not a good choice.

换句话说,不要做您想做的事情.将有关如何执行操作的知识放入模型中,但将控制权放在可以由谁执行的控件中.

In other words, don't do what you're trying to do. Put the knowledge of how to do things in your model, but put controls around who can do them in the controller.

另一方面,如果由于某种原因试图存储当前用户,则应该通过某种关联(或嵌套文档,因为您使用的是mongo)来做到这一点.在这种情况下,不要在模型内部使用current_user,而是在用户上创建attr_accessor,将模型实例上的用户设置为控制器中的current_user,然后根据需要保存它到您的回调中.

On the other hand, if you're trying to store the current user for some reason, then you should do that by some sort of association (or nested document, since you're using mongo). In that case, don't use current_user inside the model, but rather make an attr_accessor on user, set the user on the instance of your model to the current_user in the controller, and then save it how you need to in your callback.

这篇关于有哪些好的方法可以获取模型中的当前用户详细信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆