Rails 3 devise,模型中无法访问current_user? [英] Rails 3 devise, current_user is not accessible in a Model ?

查看:55
本文介绍了Rails 3 devise,模型中无法访问current_user?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的project.rb模型中,我试图创建一个具有动态变量的范围:

in my project.rb model, I'm trying to create a scope with a dynamic variable:

scope :instanceprojects, lambda { 
    where("projects.instance_id = ?", current_user.instance_id)
} 

我收到以下错误:

undefined local variable or method `current_user' for #<Class:0x102fe3af0>

在控制器中,我可以访问 current_user.instance_id ...模型无法访问它是有原因的吗?此外,这是否是创建上述范围的合适位置,还是属于控制器的范围?

Where in the controller I can access current_user.instance_id... Is there a reason the model can't access it and a way to get access? Also, is this the right place to create a scope like the above, or does that belong in the controller?

推荐答案

正如您已经指出的,这没有多大意义。 current_user根本不属于模型逻辑,应该在控制器级别进行处理。

This doesn't make much sense, as you already pointed. The current_user doesn't belong to model logic at all, it should be handled on the controller level.

但是您仍然可以像这样创建范围,只需将参数传递给

But you can still create scope like that, just pass the parameter to it from the controller:

scope :instanceprojects, lambda { |user|
    where("projects.instance_id = ?", user.instance_id)
} 

现在您可以在控制器中调用它了:

Now you can call it in the controller:

Model.instanceprojects(current_user)

这篇关于Rails 3 devise,模型中无法访问current_user?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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