使用"current_user";在Ruby on Rails中的模型中 [英] Using "current_user" in models in Ruby on Rails

查看:109
本文介绍了使用"current_user";在Ruby on Rails中的模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Devise,它在助手中提供了"current_user"方法,以便可以在视图和控制器中使用.

I'm using Devise and it offers "current_user" method in helpers, so that I can use in views and controllers.

但是,现在我想访问模型中的"current_user"方法.这就是我现在在控制器中拥有的东西.

However now I'd like to access to the "current_user" method in the models. Here's what I have in controllers now.

def create
  set_email_address(params[:email_address])
  Comment.new(params[:content], set_email_address)
  # [snip]
end

private
def set_email_address(param_email)
  if current_user
    @email_address = current_user.email
  else
    @email_address = param_email
  end
end

我想将"set_email_address"移动到模型中,因为我认为这是一种逻辑,应该将其交给模型.我打算将这种方法与Rails回调之一联系起来.

I would like to move the "set_email_address" to a model because I think that is a logic and should be handed in the model. I'm planning on hooking up this method with one of the Rails callbacks.

推荐答案

老实说,

In all honesty, this answer pretty much sums it up. This doesn't belong in Model logic at all. As the other answer also says though, you can and should pass the current_user value from the controller if you'd like to use it inside your model.

这篇关于使用"current_user";在Ruby on Rails中的模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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