ARemesal
ARemesal

Reputation: 2963

Two controllers for one shared view in Ruby on Rails

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?

I've though two options:

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.

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

Thanks in advance.

Upvotes: 27

Views: 13738

Answers (5)

carlosvini
carlosvini

Reputation: 1829

@bjeanes If all your delete views are the same, you can create views/default/delete.html.erb and all the delete actions will use it.

That's what i'm doing: Most of my views are on default, and i create specific ones only when needed

Update: Ok, this post is from 2009, anyway, i will keep my comment here in case someone gets here from Google like i did.

Upvotes: 0

Marnen Laibow-Koser
Marnen Laibow-Koser

Reputation: 6337

This looks like a good use case for the Cells gem.

Upvotes: 1

Rodrigo
Rodrigo

Reputation: 61

About the first answer:

If the partial must be rendered from a view:

<%= render :partial => "shared/photo" %>

and the partial must be in app/views/shared/_photo.html.erb

Upvotes: 6

Bo Jeanes
Bo Jeanes

Reputation: 6383

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.

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.

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

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.

Upvotes: 40

Keltia
Keltia

Reputation: 14743

I'd use an helper because they are shared among views. For the HTML part, I'd use partials so it would be a mix of both ways.

Upvotes: 1

Related Questions