菜单显示在所有页面上,代码复制到所有控制器中
我有一个收藏模型。我成功创建了一个 _collection.html.erb
,我在应用程序布局中使用 <%= render @collections%>
调用它。
我的问题是,在我的所有控制器方法中,我必须添加 @collections = Collection.all
我发现它非常非常难看,它会让我的集合范围很难改变,而且我确信我我缺少一个 Rails 魔法,它会更好。
有没有办法让模型数据生成部分布局,而无需在 AAAALLLLLL 控制器中使用相同的代码?
I have a collection model. I succesfully created a _collection.html.erb
that i call with <%= render @collections%>
in my application layout.
My problem is that in ALL my controlers method I must add @collections = Collection.all
I found it very very ugly,it will make my collection scope a pain to change, and I'm sure that I am missing a rails magic something that would be way nicer.
Is there a way to have a part of the layout generated by model data without having a identical piece of code in AAAALLLLLL the controllers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请注意,您的控制器都继承自
ApplicationController
。利用这一点来发挥你的优势。将before_filter
添加到ApplicationController
来加载您的集合。Notice that your controllers all inherit from
ApplicationController
. Use this to your advantage. Add abefore_filter
toApplicationController
that loads your collections.@cam 是对的。任何 Rails 项目都有一个 ApplicationController。您的控制器均以 MyController < 开头应用程序控制器,对吧?如果是这样,这意味着您可以在 ApplicationController 中创建一个 before_filter ,它将被所有控制器继承。为此:
从现在开始,您可以在所有控制器中使用@collections(只要它们继承自ApplicationController)
@cam was right. Any rails project has an ApplicationController. Your controllers all start with MyController < ApplicationController, right? If so, that means you can create a before_filter in your ApplicationController, which will be inherited by all your controllers. To do so :
From now on, you can use @collections from all your controllers (as long as they inherited from ApplicationController)