Rails keeps ignoring an IF statement inside the view

112 views Asked by At

I am writing an application where I want to list blog posts according to date they were created on the main index page. So lets say if I have 10 blog posts that were created today I would want to have smth like this come on the index page of the app..

Today:

POST 1

POST 2

POST 3

... so on

However, I have this...

Today:

POST 1

Today:

POST 2

Today:

POST 3

... so on

The following is my code..

index.html.erb

<% @posts.reverse.each do |post| %>

    <% flag = true %>
    <% if post.date.day < Time.now.day && 
          post.date.day >= (Time.now.day - 1.day) %>

        <!-- This IF statement gets ignored -->  
        <% if flag == true %>
            <%= "Today" %>
            <% flag = false %>
            <br />
        <% end %>

        <tr>
            <td><p>IMAGINE THIS SENTENCE IS ONE POST</p></td>
        </tr>

    <% end %>
<% end %>

The if statement that gets ignored inside the code acts as a flag, so that it should execute only once per group of posts with the same date. But, Rails seems to completely ignore it for some reason. If someone could help me correct this issue or nudge me in the right direction, your help would be greatly appreciated.

1

There are 1 answers

0
Pablo On BEST ANSWER

It's not that the if is being ignored, but that on each post the flag is being set to true again.

The first time you set the flag has to be outside of the iteration, like this:

<% flag = true %>

<% @posts.reverse.each do |post| %>

    <% if post.date.day < Time.now.day && 
          post.date.day >= (Time.now.day - 1.day) %>

        <% if flag == true %>
            <%= "Today" %>
            <% flag = false %>
            <br />
        <% end %>

        <tr>
            <td><p>IMAGINE THIS SENTENCE IS ONE POST</p></td>
        </tr>

    <% end %>
<% end %>