Problems with Group_by Rails

2

It happens that I use a group_by to divide the posts according to their year by means of a scope, and it works great I print the posts in groups per year, the problem is that when migrating to Rails5, always I divided them but I printed the other post but not correspond to that year, if I have a post of 2014, I printed all, then the next group a post of 2015, I printed below all others, I do not know exactly what will be happening, I leave my code, for suggestions and help, greetings!

Index.html.erb

<% @enterprises.group_by { |a| a.created_at.year }.each do |year, enterprises| %>
      <h5><b><%= year %></b></h5>
    <% @enterprises.each do |enterprise| %>
        <div class="main-section">
          <h5><b><%= enterprise.name %></b></h5>
          <p><%= enterprise.enterprise_tag.name %></p>
          <p><%= truncate(enterprise.about, length: 140) %></p>
        </div>
      <% end %>
    <% end %>

enterprise.rb

class Enterprise < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  def self.year
     where(created_at: Time.zone.now.beginning_of_year..Time.zone.now.end_of_year)
  end

end
    
asked by Hector Hernandez 24.11.2016 в 04:52
source

1 answer

0

I solved it, my friend, after turning it over, I asked myself why I was doing a double impression of data, until I realized that in the second each one did not call the variable "enterprise" but called it back from this form "@enterprise", that is, the correct thing will be like this:

<% @enterprises.group_by { |a| a.created_at.year }.each do |year, enterprises| %>
      <h5><b><%= year %></b></h5>
      <% enterprises.each do |enterprise| %>
       <!-- contenido -->
      <% end %>
<% end %>

Greetings, I will leave the publication for future references

    
answered by 23.01.2018 в 13:19