在模型中无法访问

在模型中无法访问

本文介绍了Rails 3 设计,在模型中无法访问 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 设计,在模型中无法访问 current_user ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 06:21