AnthonyGalli.com AnthonyGalli.com - 6 months ago 11
Ruby Question

How to render only notes that equal date?

Instead of showing all the notes per day, how can we only show one note per day, the note whose

note.note_date == date
?

Day 1: Notes/notes # Shows both Day 1 and Day 3 note. Only want to show Day 1 note
Day 2: Notes/form
Day 3: Notes/notes # Shows both Day 1 and Day 3 note. Only want to show Day 3 note
Day 4: Notes/form
Day 5: Notes/form


challenges/show

<% @challenge.dates_challenged.first(@challenge.days_challenged).each_with_index do |date, i| %>
Day <%= i + 1 %>
<% if @notes.any? { |note| note.notes_date.strftime("%m/%d/%y") == date.strftime("%m/%d/%y") } %>
<%= render 'notes/notes' %>
<% else %>
<%= render 'notes/form', :date => date %>
<% end %>
<% end %>


notes/notes

<% @notes.each do |note| %>
<%= note.notes_text %>
<% end %>


notes/form

<%= form_for [@notable, @note] do |f| %>
<%= f.text_area :notes_text, placeholder: 'Enter Recap' %>
<%= f.date_select :notes_date, selected: date, :order => [:month, :day, :year] %>
<% end %>


challenges_controller

def show
@notable = @challenge
@notes = @notable.notes
@note = Note.new
end


To recap, a user creates a challenge. A challenge has the attribute
days_challenged
. The user chooses how many days will be challenged, i.e. 10, 15, 30, etc. For each of those days a
notes/form
will be rendered. If a
note.notes_date
equals a respective day then how can we only show that one note in place of
notes/form
?

Answer
<% if @notes.any? 
  @today_notes = @notes.select{ |note| note.notes_date.strftime("%m/%d/%y") == date.strftime("%m/%d/%y") } %>
  <%= render 'notes/notes' %>
<% else %>
...
<% end %>

Then use @today_notes in the notes/notes partial.

Comments