我想创建一个在所有控制器和视图中可用的方法
我正在制作一个电子商务应用程序,其中类别在所有页面的侧栏中都可见。我在应用程序控制器中编写了一个方法
def categories
@categories = Category.all
end
,但是如何让该方法默认可供所有控制器和操作使用,这样我就不必在每个操作中专门调用该方法
def list
categories
@products = Product.order('title').page(params[:page]).per(4)
end
i am making a ecommerce application in which the categories are visible in side bar on all pages. i wrote a method in application controller
def categories
@categories = Category.all
end
but how can i make this method available to all controllers and actions by default so that i dont have to specifically call this method in every action
def list
categories
@products = Product.order('title').page(params[:page]).per(4)
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在
application_controller.rb
中定义您的方法,并且由于每个其他控制器都继承自该方法,因此该方法将可供所有控制器使用。另外,要使其成为视图中可用的辅助方法,您可以在application_controller.rb
中输入helper_method :my_method
。现在,为了在控制器中的任何其他操作之前自动评估它,您可以使用 before_filter。添加
before_filter :my_method
在控制器中,您希望在执行任何操作之前或在 application_controller.rb 中评估此方法
You can define your method in
application_controller.rb
and since every other controller inherits from this one, that method will be available to all the controllers. Also, to make it a helper method for it to be available in the views, you can sayhelper_method :my_method
in theapplication_controller.rb
.Now, for it to be automatically evaluated before any other action in a controller, you can use a before_filter. Add
before_filter :my_method
in the controller you want this method to be evaluated before any action or in the application_controller.rb
也许最正确的方法是使用宝石细胞。绝对应该尝试:http://cells.rubyforge.org/
Maybe the most proper way is to use gem cells. Definitely should try: http://cells.rubyforge.org/
如果您希望某些内容必须贯穿整个应用程序,例如本例中的:@categories ,那么请编写一个帮助程序。
在
app/helpers/application_helper.rb
If you want something that has to be across the entire application, like in this case : @categories , then write a helper.
in
app/helpers/application_helper.rb
我不认为有办法在全球范围内运行。您可以在
before_filter
中运行它,以便在每个操作之前调用它,但您必须在每个控制器中再次指定它!我的建议是将类别侧边栏内容放在包含如下调用的部分中:
然后您可以简单地将
render
调用添加到您的layout/application.html.erb
这会为你做的!I dont thing that there is a way to run this global. You could run it in a
before_filter
so its called before each action but you must specify this in every controller again!My Suggestion would be to put the category sidebar stuff in a partial which contains a Call like this:
Then you could simply add the
render
call to yourlayout/application.html.erb
that would do it for you!