问题描述
菜鸟范围问题,我想.:\
Noob scoping issue, I imagine. :\
class ApplicationController < ActionController::Base
protect_from_forgery
@locations = get_locations
def get_locations
Location.where(:active => true).order('name').all
end
end
错误:
undefined local variable or method `get_locations' for ApplicationController:Class
两个问题:1)错误是怎么回事?我是否错误地调用了该方法?2) 如何从子类控制器访问此方法?
Two questions:1) What's with the error? Am I calling the method incorrectly?2) How do I access this method from a sub-classed controller?
推荐答案
您正在类范围内调用 get_locations
,但该方法是实例方法,而不是类方法.例如,如果您使用 def self.get_locations
,那么您将提供一个类方法,您可以在类范围内使用其中一个方法(在定义它之后,而不是像之前那样).
You're calling get_locations
within the class scope, but the method is an instance method, not a class method. If for example you used def self.get_locations
then you would be providing a class method, one of which you can use within the class scope (after you have defined it, not before like you're doing).
这里的问题是逻辑,这个方法是干什么用的?你打算用 @locations
做什么?如果要进入您的应用程序视图,那么您应该将此方法放入ApplicationHelper
模块中,并从相关操作内部调用它.如果您希望在另一个控制器的另一个视图中使用它,并且您希望在 locations
方法中使用 @locations
,那么您的设置可能如下所示:
The problem here is the logic, what is this method for? What do you intend to use @locations
for? If it's to go inside your application view, then you should put this method into the ApplicationHelper
module, and call it from inside the relevant action. If you'd like it in another view on another controller and you'd like to use @locations
inside your locations
method, perhaps your setup might look something like this:
PagesController
class PagesController < ActionController::Base
def locations
@locations = Location.where(:active => true).order('name').all
end
end
locations.html.erb
<% @locations.each do |location| %>
<%= # do something with 'location' %>
<% end %>
如果你想在你的 application.html.erb
中使用它,你可以将它简化一些..
If you'd like to use this inside of your application.html.erb
you can simplify it quite some..
应用控制器
class ApplicationController < ActionController::Base
protect_from_forgery
def locations
Location.where(:active => true).order('name').all
end
end
application.html.erb
<% locations.each do |location| %>
<%= # do something with location %>
<% end %>
答案归结为逻辑,要真正弄清楚您在寻找什么,可能需要更多详细信息.
The answer boils down to logic, and to really figure out exactly what you're looking for, more details would probably be required.
这篇关于rails:如何访问应用程序控制器中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!