gpt4 book ai didi

ruby-on-rails - rails : how do i access a method in my application controller?

转载 作者:行者123 更新时间:2023-12-04 03:30:49 26 4
gpt4 key购买 nike

菜鸟范围问题,我想。 :\

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)如何从子类 Controller 访问此方法?

最佳答案

您调用get_locations在类范围内,但该方法是实例方法,而不是类方法。例如,如果您使用了 def self.get_locations那么你将提供一个类方法,其中一个你可以在类范围内使用(在你定义它之后,而不是像你正在做的那样之前)。

这里的问题是逻辑,这个方法是干什么用的?你打算用什么@locations为了?如果要进入您的应用程序 View ,那么您应该将此方法放入 ApplicationHelper模块,并从相关操作内部调用它。如果您想在另一个 Controller 上的另一个 View 中使用它,并且想使用 @locations在您的locations 内方法,也许您的设置可能如下所示:

页面 Controller

class PagesController < ActionController::Base
def locations
@locations = Location.where(:active => true).order('name').all
end
end

位置.html.erb
<% @locations.each do |location| %>
<%= # do something with 'location' %>
<% end %>

如果你想在你的 application.html.erb 中使用它你可以简化一些..

应用 Controller
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 %>

答案归结为逻辑,要真正弄清楚你在寻找什么,可能需要更多细节。

关于ruby-on-rails - rails : how do i access a method in my application controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4381436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com