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

查看:66
本文介绍了使用“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.

推荐答案

老实说,这个答案 几乎总结了它.这根本不属于模型逻辑.正如另一个答案也说的那样,如果您想在模型中使用它,您可以并且应该从控制器传递 current_user 值.

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天全站免登陆