菜单显示在所有页面上,代码复制到所有控制器中

发布于 2024-10-18 06:13:04 字数 310 浏览 0 评论 0原文

我有一个收藏模型。我成功创建了一个 _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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

臻嫒无言 2024-10-25 06:13:04

请注意,您的控制器都继承自 ApplicationController。利用这一点来发挥你的优势。将 before_filter 添加到 ApplicationController 来加载您的集合。

Notice that your controllers all inherit from ApplicationController. Use this to your advantage. Add a before_filter to ApplicationController that loads your collections.

自由范儿 2024-10-25 06:13:04

@cam 是对的。任何 Rails 项目都有一个 ApplicationController。您的控制器均以 MyController < 开头应用程序控制器,对吧?如果是这样,这意味着您可以在 ApplicationController 中创建一个 before_filter ,它将被所有控制器继承。为此:

/app/controllers/application_controller.rb

before_filter :load_collection

def load_collection
    @collections = Collection.all
end

从现在开始,您可以在所有控制器中使用@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 :

/app/controllers/application_controller.rb

before_filter :load_collection

def load_collection
    @collections = Collection.all
end

From now on, you can use @collections from all your controllers (as long as they inherited from ApplicationController)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文