Ruby on Rails 中一个共享视图的两个控制器 [英] Two controllers for one shared view in Ruby on Rails

查看:20
本文介绍了Ruby on Rails 中一个共享视图的两个控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个控制器分别用于两个模型,例如照片和类别.每个控制器中的 index 和 show 方法非常相似,并且视图相同.两种模型共享视图的最佳方法是什么?

I have two controllers for two respective models, by example, photos and categories. index and show methods are very similar in each controller, and the views are identical. What is the best method for share the view by the two models?

我有两个选择:

  • 使用帮手.在helper中会放入view的代码,并且会从每个view(photos/views和categories/views)调用helper

  • Use a helper. In the helper will put the code for the view, and will call the helper from each view (photos/views and categories/views)

在每个视图中使用局部.我认为这是一个更干净的解决方案,但在编写此解决方案时,我的脑海中出现了巨大的 DRY.

Use a partial in each views. I think it's a more clean solution, but I see huge DRY's in my mind when going to code this solution.

因此,我有来自两个模型的两个控制器,每个控制器都暴露一个 @photo 对象(带有所有照片的照片控制器,以及仅带有所选类别照片的类别控制器),我需要一个视图来显示两者.

So, I have two controllers from two models, each one at and exposes a @photo object (photos controller with all the photos, and categories controller with just the selected categorie's photos) and I need one view to show both.

我正在为此寻找一个优雅的解决方案,抱怨 REST 和 DRY 原则.有什么想法吗?

I'm looking for an elegant solution for this, complaining REST and DRY principes. Any idea?

提前致谢.

推荐答案

我的一个项目遇到了类似的情况.大多数控制器的所有删除视图的样式都相同,显示相同的确认框,并简单地呈现正在删除的任何对象的可预测显示.

I have a similar situation with one of my projects. All the delete views for most controllers are styled the same way, display the same confirmation boxes, and simply renders a predictable display of whatever object is being deleted.

在我看来,解决方案非常简单和优雅.简单地说,我们(开发人员)所做的是在 app/views 中创建一个名为 shared 的新目录,并将共享视图放在那里.这些可以是完整的模板文件,也可以只是部分文件.

The solution was quite simple and elegant in my opinion. Simply put, what we (the developers) did was create a new directory in app/views called shared and put shared views in there. These could be full template files or just partials.

我建议使用共享模板(不在类别或照片视图目录中,而是在共享目录中)并从视图中手动渲染.

I would suggest using a shared template (in neither categories nor photos view directories, but rather in the shared directory) and rendering it manually from the view.

例如在控制器和文件中都有一个方法 app/views/shared/photo.html.erb:

e.g. have a method as such in both controllers and a file app/views/shared/photo.html.erb:

def show
  @photo = Photo.first # ... or whatever here
  render :template => 'shared/photo'
end

这应该会成功呈现共享模板.这是 DRYest 路线,并且不会有在每个控制器的视图目录中使用或多或少的空视图以包含共享部分时所获得的污染感,正如我理解您的问题所暗示的那样.

This should successfully render the shared template. It is the DRYest route and doesn't have the feeling of pollution you get when using a more-or-less empty view in each controller's view directory just to include a shared partial, as I understand your question is suggesting.

这篇关于Ruby on Rails 中一个共享视图的两个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆