Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails div_for vs <div>

I'm new to Ruby on Rails. In my erb files, is there any reason to use the div_for helper over just typing out the <div> tags and setting the properties as HTML? What advantage is there to using div_for, and is there a recommended best practice?

like image 972
Winston Kotzan Avatar asked Nov 07 '12 01:11

Winston Kotzan


2 Answers

I think the main reason people use the div_for helper is because it can accept an array of ActiveRecord objects as an argument. That way it becomes a short-hand combination of a loop iterator and a tag generator.

<%= div_for(@people, :class => "foo") do |person| %>
    <%= person.name %>
<% end %>
like image 182
platforms Avatar answered Sep 19 '22 07:09

platforms


div_for does some "magic" for you, in that it sets the class and ID of the element it generates.

There is no reason to choose it over a simple <div> tag if you don't intend to use those properties, or intent to use different values for them.

There is no strong convention either way. I've been writing Rails code for years and have literally never used it, put it out of your mind, it doesn't matter. There are far, far more important decisions to make, like choosing erb or haml or slim, or deciding whether to adpot CoffeeScript. Decisions that will fundamentally alter the way you write Rails code.

like image 33
meagar Avatar answered Sep 21 '22 07:09

meagar