Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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.

The other answers represent the conceptual consensus regarding the use of helpers vs. partials. Consider the following for further reading:

Basecamp dev making the case for minimizing HTML in helpers http://37signals.com/svn/posts/1108-what-belongs-in-a-helper-method

Viget dev benchmarked each and found that helpers are faster than partials http://www.viget.com/extend/helpers-vs-partials-a-performance-question/

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

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).

Partials are the part of view which can have bunch of HTML code along with ruby code. You can also use the partials in controller in render method.

In case of helpers, you can have methods for short html piece of code. You can have some calculations related methods which you want to use in your view file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top