darkginger darkginger - 4 months ago 10
Javascript Question

Making Rails loop over an element to represent items in my table

I am building a Rails app, and I am using a hexagonal grid to show links to its blog posts as an image hexagon for each post. For clarity, here's what that looks like with static posts:

<ul id="hexGrid">
<li class="hex">
<a class="hexIn" href="contact">
<img src="https://structurepoint.files.wordpress.com/2014/09/wp_20140804_041.jpg" alt="" />
<h1>This is a title</h1>
<p>Some sample text about the article this hexagon leads to</p>
</a>
</li>
<li class="hex">
<a class="hexIn" href="#">
<img src="https://structurepoint.files.wordpress.com/2014/09/wp_20140804_041.jpg" alt="" />
<h1>This is a title</h1>
<p>Some sample text about the article this hexagon leads to</p>
</a>
</li>
<li class="hex">
<a class="hexIn" href="#">
<img src="https://structurepoint.files.wordpress.com/2014/09/wp_20140804_041.jpg" alt="" />
<h1>This is a title</h1>
<p>Some sample text about the article this hexagon leads to</p>
</a>
</li>
</ul>


To see the full code for it, here's the JSFiddle.

Here's the problem. I need to make the hexagons dynamic, and I want it to generate one for each of them in my
Post
table. To do that, I tried to iterate like so:

<ul id="hexGrid">
<li class="hex">
<a class="hexIn" href="#">
<% @posts.each do |post| %>
<%= image_tag("http://www.fearthewave.com/wp-content/uploads/2016/05/bevo-768x410.png", :alt => "rss feed") %>
<h1><%= post.title %></h1>
<p><%= post.category %></p>
<% end %>
</a>
</li>
</ul>


Even though in my controller, I am setting
@posts = Post.all
and there are five posts in the database, the code above is only generating one hexagon for a post. I want the view to render 5 of them.

Is it possible to make the hexagon
<li>
dynamic?

Possible Questions




  1. There is a static image link in the iteration, why did you do that? I put that image link in as a placeholder. I haven't installed the Paperclip gem yet -- I want it to produce 5 hexagons, and it's fine that it uses a static image now. In the future, this will link to the image associated with the post.


Answer

I think you're doing the loop in the wrong place:

<ul id="hexGrid">
  <% @posts.each do |post| %>
  <li class="hex">
    <a class="hexIn" href="#">
      <%= image_tag("http://www.fearthewave.com/wp-content/uploads/2016/05/bevo-768x410.png", :alt => "rss feed") %>
      <h1><%= post.title %></h1>
      <p><%= post.category %></p>
    </a>
  </li>
  <% end %>
</ul>