views:

455

answers:

4

In a rails application, in which situation would you use a partial and when would you use a helper? I find both very similar, since they represent markup fragments.

Is there a convention around this? which is the 'rails way' of using them?

Thanks!

+5  A: 

I guess my rule of thumb is to use a helper to build a single "unit" of display -- like a span containing a link -- and to use a partial to build a more complex unit of display composed of more than one "unit" of display -- like a grid or a menu.

tvanfosson
+1  A: 

I use helpers when the code is likely to be used again in other projects, and partials for code specific to the project.

anithri
+1  A: 

I use partials as subtemplates (i.e., something with lots of markup that gets used again and again, like a blog post blurb), and helpers to handle display more logic-y things (a div that's only visible to admins, for instance).

zenazn
+4  A: 

A partial is a view fragment, a piece of a view that is useful in multiple places and is pulled out so as to remove duplication. Bottom line, however, is that views - standalone or partial - are for presentation.

As you know, controllers are for processing logic. It is inevitable, however, that you will need some logic processing when presenting a view. So, for instance, if you have some presentation piece that is only available to admins, you might extract that logic to a helper and keep the view "pure" and presentation-only. Helpers will inevitably contain presentation code - html tags and such - but that is a by-product of their use, not their primary function.

You can also combine the two - a partial for the admin presentation and another for the user presentation, and a helper with the logic to determine which one is rendered in a particular situation.

Just my $.02.

Yardboy
But rails uses helpers for presentation only (like checkboxes and textfields)
Pablo Fernandez