AnthonyGalli.com
AnthonyGalli.com

Reputation: 2866

Border Around All Objects NOT Each Object?

How can I put a challenges-border around all the Date.current challenges?

The problem with this first attempt is that the border is placed around each challenge, but I want the border to be placed around all the challenges that are Date.current.

Attempt #1

<% @challenges.each do |challenge| %>
  <% if challenge.deadline == Date.current %>
    <div class="challenges-border">
      <%= challenge.deadline %>: <%= challenge.action %>
    </div>
  <% else %>
    <%= challenge.deadline %>: <%= challenge.action %>
  <% end %>
<% end %>

enter image description here

Attempt #2

I get error deadline undefined method

<% if @challenges.deadline == Date.current %>
  <div class="challenges-border">
<% end %>

<% @challenges.each do |challenge| %>
  <%= challenge.deadline %>: <%= challenge.action %>
<% end %>

<% if @challenges.deadline == Date.current %>
  </div>
<% end %>

Attempt #3

This doesn't work because I want the challenges to be organized in descending order via deadline, which means Date.current challenges could appear in the middle of the list instead of listing them all as @todays_challenges at the end.

<% @challenges.each do |challenge| %>
  <%= challenge.deadline %>: <%= challenge.action %>
<% end %>

<div class="challenges-border">
  <% @todays_challenges.each do |challenge| %>
    <%= challenge.deadline %>: <%= challenge.action %>
  <% end %>
</div>

Upvotes: 0

Views: 21

Answers (1)

Hieu Pham
Hieu Pham

Reputation: 6707

Ideally, you can separate your @challenge by 2 groups, 1st group with border, the remaining without border:

Temporary solution

<% current_date = Date.current %>
<% current_challenges = @challenges.select{ |challenge| challenge.deadline == current_date } %>
<% remaining_challenges = @challenges - current_challenges %>

<% current_challenges.each do |challenge| %>
  <div class="challenges-border">
    <%= challenge.deadline %>: <%= challenge.action %>
  </div>
<% end %>

<% remaining_challenges.each do |challenge| %>
  <%= challenge.deadline %>: <%= challenge.action %>
<% end %>

Refactored solution

  • Separate your @challenges in your controller instead
  • Move the logic out of view, you may use view helper or view presenter!

Upvotes: 1

Related Questions