Rails 3 ActiveRecord group_by sort by count

Posted by Craig on Stack Overflow See other posts from Stack Overflow or by Craig
Published on 2011-01-04T02:52:14Z Indexed on 2011/01/04 2:53 UTC
Read the original article Hit count: 176

The following view code generates a series of links with totals (as expected):

<% @jobs.group_by(&:employer_name).sort.each do |employer, jobs| %>
    <%= link_to employer, jobs_path() %> <%= "(#{jobs.length})" %>
<% end %>

However, when I refactor the view's code and move the logic to a helper, the code doesn't work as expect.

view:

<%= employer_filter(@jobs_clone) %>

helper:

def employer_filter(jobs)
    jobs.group_by(&:employer_name).sort.each do |employer,jobs|
        link_to employer, jobs_path()
    end   
end

The following output is generated:

<Job:0x10342e628>#<Job:0x10342e588>#<Job:0x10342e2e0>Employer A#<Job:0x10342e1c8>Employer B#<Job:0x10342e0d8>Employer C#<Job:0x10342ded0>Employer D#

What am I not understanding? At first blush, the code seems to be equivalent.

© Stack Overflow or respective owner

Related posts about refactoring

Related posts about view