以两种不同方式呈现同一事物的最佳实践是什么?
我有一个 - 比如说 Actor
- 模型和具有经典 show
动作的相关控制器,该动作显示演员的完整列表以及有关他们的各种信息(例如他们主演的电影)中等)。
现在,我想检索 show
操作所需的完全相同的信息,但以不同样式的部分显示它们,因为该部分 - 比如说 _search_results
- 必须用于创建一个小的“键入时搜索”框。
将 show
操作想象为一个显示文件夹和文件的 Finder 窗口,将我的部分想象为当您在 Spotlight 上搜索某些内容时出现的下拉列表。
当然,我希望尽可能保持干燥,所以我想知道执行此操作的最佳实践是什么,同时几乎不在我的actors_controller中重复代码,因为部分所需的信息是与已为 show
视图生成的 show
操作完全相同。
谢谢。
编辑(注意) 当然,我希望从控制器内部渲染部分内容,因为我不希望所有应用程序布局都显示在搜索结果框中!
I got a - say Actor
- model and the relative controller with a classical show
action that displays the complete list of actors and various information about them (e.g. movies they've starred in, etc.).
Now, I'd like to retrieve the exact same information I need for my show
action, but to show them in a partial with a different style, since this partial - say _search_results
- has to be used to create a small "search-as-you-type" box.
Imagine the show
action as a Finder window displaying folders and files and my partial as the dropdown list that appears when you search something on Spotlight.
Of course I would like to stay as DRY as possible and so I'm wondering what is the best practice to do this, while almost not repeating code in my actors_controller
, since the information needed by the partial are exactly the same that the show
action already produces for the show
view.
Thanks.
Edit (N.B.) Of course I want the partial to be rendered from inside the controller, because I don't want all my application layout to be shown in the search result box!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对此的经典建议是将信息组件粘贴在模型中,以便多个控制器操作可以访问它而无需重复。命名范围等使这一切变得很容易。
http://weblog.jamisbuck.org/2006/10/18 /瘦控制器胖模型
The classic advice on this is to stick the information assembly in the model, so it can be accessed by multiple controller actions without duplication. Named scopes and the like make much of this easy to do.
http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model
您想使用演示者。它是一个类,封装了为您正在使用的模板/部分准备数据所需的所有逻辑。然后,您可以在渲染模板之前在控制器中创建该演示者的实例。这是一篇关于 Presenter 模式以及何时使用它的好文章。
http://kpumuk.info/ruby-on- Rails/简化您的 ruby-on-rails 代码/
You want to use a Presenter. It is a class that encapsulates all the logic needed to prepare the data for the template/partial you are using. Then you can create an instance of that presenter in your controller before you render the template. Here is a good write up about the Presenter pattern and when to use it.
http://kpumuk.info/ruby-on-rails/simplifying-your-ruby-on-rails-code/