Search code examples
ruby-on-railsrubyrails-activerecordactive-record-query

Why is my iteration through records adding whole object dump in a strange place?


I have two Models, Habit and HabitLog.

For simplicity Habit holds a name and has many HabitLogs. HabitLog holds a date and status.

I want to create a view for specific date and list all the Habits with status for given date.

To get records, but keep association I used this query in my controller:

habit_log_controller.rb

def show
  @habit_logs = HabitLog.where(log_date: '2015-07-15').includes(:habit).order("habits.position")
end

Then in my view I have

show.html.erb

<ul>
  <%= @habit_logs.each do |habit_log| %>
    <li>
      <%= habit_log.habit.name + " " + habit_log.status %>
    </li>
  <% end %>
</ul>

It works, meaning in lists all the Habit names and status for given day, but it pastes the whole array in a strange place, after the li tag, but inside ul.

Page source

<ul>

  <li>
     Waga 87
  </li>

  <li>
     Higiena 1
  </li>

  <li>
     Siłownia 0
  </li>
  [#&lt;HabitLog id: 1, log_date: &quot;2015-07-15&quot;, status: &quot;87&quot;, habit_id: 1, created_at: &quot;2015-07-15 11:37:21&quot;, updated_at: &quot;2015-07-15 11:37:21&quot;&gt;, #&lt;HabitLog id: 2, log_date: &quot;2015-07-15&quot;, status: &quot;1&quot;, habit_id: 2, created_at: &quot;2015-07-15 11:37:28&quot;, updated_at: &quot;2015-07-15 11:37:28&quot;&gt;, #&lt;HabitLog id: 3, log_date: &quot;2015-07-15&quot;, status: &quot;0&quot;, habit_id: 3, created_at: &quot;2015-07-15 11:37:30&quot;, updated_at: &quot;2015-07-15 11:37:30&quot;&gt;]

</ul>

I figure this has to do with my use of .includes(:habit), but I have no idea how to deal with it.


Solution

  • The problem is this line

    <%= @habit_logs.each do |habit_log| %>
    

    should be

    <% @habit_logs.each do |habit_log| %>
    

    Imp Note:

    <% %> # Executes the code.
    
    <%= %> # Prints the output.