Ruby / Rails - dynamically create a table for a variable number of cells

I am trying to display objects in my model as a table, but it is difficult for me to create columns and columns dynamically.

I have a model called "Pictures", and currently I'm showing them all on the looooong list.

<% for picture in @pictures %> <p><%= image_tag(picture.url) %></p> <% end %> 

How can I turn this into a table in rails view?

 <table> <tr> <% for picture in @pictures %> <td> <%= image_tag(picture.url) %> </td> ** Here where I'm confused..How can I write after 6 cells create a new row?? ***** <% end %> </table> 

So, the question is really related to how to break this data type in the view.

+6
source share
5 answers

Take a look at the enumerated method .each_slice.

http://www.ruby-doc.org/core/classes/Enumerable.html#M001514

With it, you can do something line by line:

 <table> <% @pictures.each_slice(6) do |slice| %> <tr> <% slice.each do |picture| %> <td> <%= image_tag(picture.url) %> </td> <% end %> </tr> <% end %> </table> 

You may need to play a little to fill the last line beautifully, but this should help you.

+11
source

I am really digging out each_slice solution. Just thought that I would call back if you wanted to have a non-tabular view, you could find out your maximum width and maximum height for your images and set the container around your photos and just use css to pop up together. Each line will contain, however, many will fit in your containing div.

View

 <% for picture in @pictures %> <div class="photo"> <%= image_tag(picture.url) %> </div> <div class="float_clear"></div> <% end %> 

CSS

 .photo {height: 150px; width: 150px; float:left;margin:0 10px; 10px 0;} .photo img{max-height: 150px; max-width: 150px;} .float_clear{clear:both;} 
+1
source

I am sure there are some helpers on Ruby on rails for this, but if not, here is how I approached this kind of layout in my last life as a low-level php developer:

Keep the score modulo 6 (i.e. i = (i + 1)% 6). If I == 0, output <tr> </tr>.

So something like:

 <% i = 0 %> <tr> <% @pictures.each do |picture| i = (i + 1) % 6 %> <%= '<tr></tr>' if i == 0 %> <td> <%= image_tag(picture.url) %> </td> <% end %> </tr> 
0
source

I would use% (module), something like this:

 <table> <% rows = 0 %> <% @pictures.each do |picture| %> <%= "<tr>" if rows % 6 %> <td><%= image_tag(picture.url) %></td> <% rows += 1 %> <%= "</tr>" if rows % 6 %> <% end %> <%= "</tr>" unless rows % 6 %> </table> 
0
source

Another nice way to do this in rails is to use the in_groups_of method.

So you may have

 <table> <% @pictures.in_groups_of(6, false) do |group| %> <tr> <% group.each do |picture| %> <td> <%= image_tag(picture.url) %> </td> <% end %> </tr> <% end %> </table> 

Here's the documentation for this method: http://apidock.com/rails/Array/in_groups_of

0
source

Source: https://habr.com/ru/post/891681/


All Articles